LibWeMeet =
/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by aragornzhao on 2018/05/18
 * 功能： WeMeetSDK
 */

var AuthService = __webpack_require__(1);
var MeetingUserController = __webpack_require__(6);
var MeetingAudioController = __webpack_require__(8);
var MeetingVideoController = __webpack_require__(9);
var SettingService = __webpack_require__(10);
var PreMeetingManager = __webpack_require__(13);
var Scout = __webpack_require__(14);
var Constants = __webpack_require__(2);

/**
 * the main of weMeetSDK
 */

var WeMeetSDK = function () {
    function WeMeetSDK() {
        _classCallCheck(this, WeMeetSDK);

        this.authService = AuthService.getInstance();
        this.meetingUserController = MeetingUserController.getInstance();
        this.meetingAudioController = MeetingAudioController.getInstance();
        this.meetingVideoController = MeetingVideoController.getInstance();
        this.preMeetingManager = PreMeetingManager.getInstance();
        this.settingService = SettingService.getInstance();
        this.scout = Scout.getInstance();
        this.constants = Constants;
        this.appId = "";
    }

    /**
     * 获取单例对象
     * @returns {WeMeetSDK}
     */


    _createClass(WeMeetSDK, [{
        key: "setAppId",
        value: function setAppId(appId) {
            this.appId = appId;
            this.meetingUserController.app_id = this.appId;
            this.preMeetingManager.app_id = this.appId;
        }
    }, {
        key: "getVersion",
        value: function getVersion() {
            return Constants.Version;
        }
    }, {
        key: "queryAuthService",
        value: function queryAuthService() {
            return this.authService;
        }
    }, {
        key: "queryMeetingUserController",
        value: function queryMeetingUserController() {
            return this.meetingUserController;
        }
    }, {
        key: "queryMeetingAudioController",
        value: function queryMeetingAudioController() {
            return this.meetingAudioController;
        }
    }, {
        key: "queryMeetingVideoController",
        value: function queryMeetingVideoController() {
            return this.meetingVideoController;
        }
    }, {
        key: "querySettingService",
        value: function querySettingService() {
            return this.settingService;
        }
    }, {
        key: "queryPreMeetingManager",
        value: function queryPreMeetingManager() {
            return this.preMeetingManager;
        }
    }, {
        key: "getSDKConstants",
        value: function getSDKConstants() {
            return this.constants;
        }
    }, {
        key: "setTimeout",
        value: function setTimeout(numms) {
            this.authService.xmppService.timeout = numms;
        }
    }, {
        key: "getTimeout",
        value: function getTimeout() {
            return this.authService.xmppService.timeout;
        }
    }, {
        key: "isSupportWebRTC",
        value: function isSupportWebRTC() {
            return this.scout.isSupportWebRTC();
        }
    }], [{
        key: "getInstance",
        value: function getInstance(appId) {
            if (typeof appId === "undefined") {
                console.error('WeMeetSDK.getInstance(appId): you must specify appId!');
                return null;
            }
            if (WeMeetSDK.prototype.instance === undefined) {
                WeMeetSDK.prototype.instance = new WeMeetSDK();
                WeMeetSDK.prototype.instance.setAppId(appId);
            }
            return WeMeetSDK.prototype.instance;
        }
    }]);

    return WeMeetSDK;
}();

module.exports = WeMeetSDK;

/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by aragornzhao on 2018/05/14
 * 功能： 权限管理
 */

var Constants = __webpack_require__(2);
var Logger = __webpack_require__(3);
var XmppService = __webpack_require__(4);

var AuthService = function () {
    function AuthService() {
        var _this = this;

        _classCallCheck(this, AuthService);

        this.logger = new Logger();
        this.loginState = Constants.LoginState.LOGIN_STATE_NULL;
        this.xmppService = XmppService.getInstance();
        this.eventListenersMap = new Map();

        this.uid = null;
        this.onLogin = this.onLogin.bind(this);
        this.onLogout = this.onLogout.bind(this);
        this.onConnFailed = this.onConnFailed.bind(this);
        var bind_this = function bind_this(funcname) {
            return _this[funcname] = _this[funcname].bind(_this);
        };
        bind_this('login');
        bind_this('logout');
        bind_this('onLogout');
        bind_this('getLoginState');
        bind_this('registerEventHandler');
        bind_this('getEventHandler');
        bind_this('internalLogin');
        bind_this('internalLogout');

        this.xmppService.registerEventHandler("login", this.onLogin);
        this.xmppService.registerEventHandler("logout", this.onLogout);
        this.xmppService.registerEventHandler("connfailed", this.onConnFailed);
    }

    _createClass(AuthService, [{
        key: "login",


        /**
         * 登陆操作接口
         * @param authParam 登陆参数
         * @returns {number} SdkError
         */
        value: function login(authParam) {
            this.logger.info('login start');
            if (authParam.app_uid.length === 0) {
                console.error('SdkError.SDK_ERROR_INVALID_PARAMS');
                return Constants.SdkError.SDK_ERROR_INVALID_PARAMS;
            }

            if (authParam.auth_type === Constants.AuthType.AUTH_TYPE_USER) {
                if (authParam.app_token.length === 0) {
                    console.error('login: token length should be > 0');
                    return Constants.SdkError.SDK_ERROR_INVALID_PARAMS;
                } else if (authParam.app_uid.length < 3) {
                    console.error('login: uid length should be > 3');
                    return Constants.SdkError.SDK_ERROR_INVALID_PARAMS;
                }
            }

            if (this.loginState === Constants.LoginState.LOGIN_STATE_LOGOUT || this.loginState === Constants.LoginState.LOGIN_STATE_NULL) {
                this.authType = authParam.auth_type;
                this.internalLogin(authParam);
                return Constants.SdkError.SDK_ERROR_SUCCESS;
            }

            console.error('SdkError.SDK_ERROR_INVALID_OPERATION');
            return Constants.SdkError.SDK_ERROR_INVALID_OPERATION;
        }

        /**
         * 获取登陆状态
         * @returns {*}
         */

    }, {
        key: "getLoginState",
        value: function getLoginState() {
            this.logger.info(this.loginState);
            return this.loginState;
        }

        /**
         * 登出
         * @returns {number} SdkError
         */

    }, {
        key: "logout",
        value: function logout() {
            this.logger.info('logout start');
            if (this.loginState === Constants.LoginState.LOGIN_STATE_LOGIN) {
                this.logger.info('calling this.internalLogout');
                this.internalLogout();
                return Constants.SdkError.SDK_ERROR_SUCCESS;
            }
            return Constants.SdkError.SDK_ERROR_INVALID_OPERATION;
        }

        /**
         * 注释事件回调
         * @param event_key： 事件名称
         * @param callBackFun： 回调函数
         * @returns {boolean}
         */

    }, {
        key: "registerEventHandler",
        value: function registerEventHandler(event_key, callBackFun) {
            var event_list = ['login', 'logout', 'connfailed'];

            if (event_list.indexOf(event_key) === -1) {
                return false;
            }

            if (typeof callBackFun === "function") {
                this.eventListenersMap.set(event_key, callBackFun);
                return true;
            }

            return false;
        }

        /**
         * 获取事件回调函数
         * @param event_key: 事件名称
         * @returns {function} 回调函数
         */

    }, {
        key: "getEventHandler",
        value: function getEventHandler(event_key) {
            var cb = this.eventListenersMap.get(event_key);
            if (cb === undefined) {
                cb = function cb(flag, data) {};
            }
            return cb;
        }
    }, {
        key: "onLogin",
        value: function onLogin(flag, data) {
            if (flag) {
                this.loginState = Constants.LoginState.LOGIN_STATE_LOGIN;
                if (this.xmppService.jid) {
                    this.uid = this.xmppService.jid.split("/")[0];
                    this.logger.setUid(this.uid);
                    this.logger.report(1, 'login', 'login success');
                }
            } else {
                this.loginState = Constants.LoginState.LOGIN_STATE_NULL;
            }

            var cb = this.getEventHandler("login");
            cb(flag, data);
        }
    }, {
        key: "onLogout",


        /**
         * logout is euqal to, and is implemented by disconnect
         */
        value: function onLogout(flag, data) {
            console.log('auth_service logout');
            this.uid = null;
            this.logger.report(1, 'logout', 'disconnect:', data);
            this.loginState = Constants.LoginState.LOGIN_STATE_LOGOUT;
            if (this.uid) {
                this.logger.setUid(this.uid + '(disconnected)');
            }
            var cb = this.getEventHandler("logout");
            cb(flag, data);
        }

        /**
         * called when connection failed
         */

    }, {
        key: "onConnFailed",
        value: function onConnFailed(flag, data) {
            this.getEventHandler("connfailed")(flag, data);
        }
    }, {
        key: "internalLogin",
        value: function internalLogin(auth_param) {
            this.loginState = Constants.LoginState.LOGIN_STATE_LOGGINING;
            console.log('user login with uid:', auth_param.app_uid);
            this.logger.report(1, 'login', 'user login with uid:', auth_param.app_uid, 'with instance id:', Constants.INSTANCE_ID, 'with sdk version:', Constants.Version);
            var jid = auth_param.app_uid + "/" + Constants.INSTANCE_ID.toString();
            var pwd = auth_param.app_token;
            var authInfo = auth_param.token_obj;
            this.xmppService.connect(jid, pwd, authInfo);
        }

        /**
         * 登出操作核心
         */

    }, {
        key: "internalLogout",
        value: function internalLogout() {
            this.logger.info('calling xmppService.disconnect');
            this.xmppService.disconnect();
        }
    }], [{
        key: "getInstance",
        value: function getInstance() {
            if (AuthService.prototype.instance === undefined) {
                AuthService.prototype.instance = new AuthService();
            }
            return AuthService.prototype.instance;
        }
    }]);

    return AuthService;
}();

module.exports = AuthService;

/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


// let WEMEET_WEBSOCKET_SERVER_ADDR = "http://203.195.137.116:8881/http-bind";
var WEMEET_WEBSOCKET_SERVER_ADDR = "wss://meetingwsdev.medialab.qq.com/websocket/connection";
var WEMEET_WEBSOCKET_SERVER_ADDR_TEST = "wss://xmpp.i-sharing.xyz/ws/";

var VERSION = 'v0.9.33';
var OS = 'unknown';
if (navigator) {
    OS = navigator.platform;
}

/**
 * "web" / "mp"
 */
var PLATFORM = "web";

// http://tapd.oa.com/media_lab_services/markdown_wikis/view/#1020366062007262783
var InstanceType = {
    INSTANCE_WEB: 5, //1007
    INSTANCE_MP: 8 //1109
};

var INSTANCE_ID = InstanceType.INSTANCE_WEB;

var AuthType = {
    AUTH_TYPE_USER: 1, // authrize for user type
    AUTH_TYPE_VISITOR: 2 // suthrize for visitor type
};

var LoginState = {
    LOGIN_STATE_NULL: 0, // unlogin
    LOGIN_STATE_LOGIN: 1, // is login
    LOGIN_STATE_LOGGINING: 2, // is logining
    LOGIN_STATE_LOGOUT: 3 // logout
};

var DeviceType = {
    CAMERA: 0,
    MIC: 1,
    SPEAKER: 2,
    UNKNOWN: 3
};

var SdkError = {
    SDK_ERROR_SUCCESS: 0,
    SDK_ERROR_ENGINE_NOT_INIT: 1,
    SDK_ERROR_ENGINE_INIT_ERROR: 2,
    SDK_ERROR_AV_ENGINE_ERROR: 3,
    SDK_ERROR_SERVICE_ERROR: 4,
    SDK_ERROR_NOT_IMPL: 5,
    SDK_ERROR_OUT_OF_MEMORY: 6,
    SDK_ERROR_INVALID_PARAMS: 7,
    SDK_ERROR_INVALID_OPERATION: 8,
    SDK_ERROR_NO_PEMISSION: 9,
    SDK_ERROR_UNKNOWN: 99,
    // websocket error codes start from 1000
    WEBSOCKET_ERROR_EVICTED: 4014
};

var SdkResult = {
    SDK_RESULT_SUCCESS: 0,
    SDK_RESULT_APP_AUTH_FAILED: 1,
    SDK_RESULT_USER_AUTH_FAILED: 2,
    SDK_RESULT_TIMEOUT: 3,
    SDK_RESULT_CREATE_ERROR: 4,
    SDK_RESULT_LOGOUT_ERROR: 5,
    SDK_RESULT_PARSE_ERROR: 6,
    SDK_RESULT_REQUEST_TIMEOUT: 7
};

var MediaType = {
    AUDIO: 1,
    VIDEO: 2,
    SCREEN_SHARE: 3
};

var UserState = {
    JOIN: 1,
    LEAVE: 2,
    UPDATE: 3,
    KICKED: 4
};

var SwitchReason = {
    BYSELF: 1, //1为主动:用户自己开关;
    BYHOST: 2 //2为被动:被主持人禁用
};

module.exports = {
    ConfWebSocketUrl: WEMEET_WEBSOCKET_SERVER_ADDR,
    ConfWebSocketUrlTest: WEMEET_WEBSOCKET_SERVER_ADDR_TEST,
    Version: VERSION,
    Os: OS,
    Platform: PLATFORM,
    InstanceType: InstanceType,
    INSTANCE_ID: INSTANCE_ID,
    AuthType: AuthType,
    LoginState: LoginState,
    DeviceType: DeviceType,
    SdkError: SdkError,
    SdkResult: SdkResult,
    MediaType: MediaType,
    UserState: UserState,
    SwitchReason: SwitchReason
};

/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Constants = __webpack_require__(2);

var WebLog = function () {
  function WebLog() {
    _classCallCheck(this, WebLog);

    this.logver = 1;
    this.chaos = Math.random().toString().substr(2, 8);
    this.serialnum = 1;
    this.uid = "(null)";
    this.send = function () {
      return null;
    };
    // this.setSendFunc(this.jQSend);
    this.url = "https://testweb.wemeet.tencent.com/weblog/";
  }

  _createClass(WebLog, [{
    key: "setUid",
    value: function setUid(uid) {
      this.uid = uid;
    }

    /*
     * send func
     * should be like:
     * send(contentObject, url);
     * where `contentObject` is of object type
     * and will do a POST method to web log service specified by `url`
     */

  }, {
    key: "setSendFunc",
    value: function setSendFunc(send_func) {
      this.send = send_func;
    }

    /*
     * make sure jQuery is loaded
     */

  }, {
    key: "jQSend",
    value: function jQSend(obj, url) {
      $.ajax({
        type: "POST",
        url: url,
        dataType: 'json',
        data: obj,
        success: function success(json) {
          // console.log('web log recv rep:', json);
        },
        error: function error(err) {
          // console.error('web log recv error:', err);
        }
      });
    }
  }, {
    key: "log",
    value: function log(lv, classid, content) {
      lv = Number(lv);
      if (isNaN(lv) || lv < 1) {
        console.log('web log error: lv must be greater than 0!!');
        throw new Error('web log error: lv must be greater than 0!!');
      }

      if (typeof classid !== 'string') {
        console.log('web log error: classid must be a string!!');
        throw new Error('web log error: classid must be a string!!');
      }

      if ((typeof content === "undefined" ? "undefined" : _typeof(content)) === 'object') {
        try {
          content = JSON.stringify(content);
        } catch (err) {
          console.log("web log error: when turning content(object) into string:", err);
          throw new Error("web log error: when turning content(object) into string");
        }
      }

      if (typeof content !== 'string') {
        console.log('web log error: invalid content:', content);
        throw new Error('web log error: invalid content:');
      }

      content.replace(/\r|\n/g, " ");

      var logObj = {
        logver: this.logver,
        uid: this.uid,
        chaos: this.chaos,
        serialnum: this.serialnum++,
        clientstamp: new Date().getTime(),
        lv: lv,
        classid: classid,
        content: content
      };

      this.send(logObj, this.url);
      console.log(content);
    }
  }], [{
    key: "getInstance",
    value: function getInstance() {
      if (WebLog.prototype.instance === undefined) {
        WebLog.prototype.instance = new WebLog();
      }
      return WebLog.prototype.instance;
    }
  }]);

  return WebLog;
}();

var Logger = function () {
  function Logger() {
    _classCallCheck(this, Logger);
  }

  _createClass(Logger, [{
    key: "debug",
    value: function debug(logParam) {
      var _console;

      for (var _len = arguments.length, logParamRest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        logParamRest[_key - 1] = arguments[_key];
      }

      (_console = console).log.apply(_console, [logParam].concat(logParamRest, ['\n', new Error().stack.split("\n")[2]]));
    }
  }, {
    key: "info",
    value: function info(logParam) {
      var _console2;

      for (var _len2 = arguments.length, logParamRest = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
        logParamRest[_key2 - 1] = arguments[_key2];
      }

      (_console2 = console).log.apply(_console2, [logParam].concat(logParamRest, ['\n', new Error().stack.split("\n")[2]]));
    }
  }, {
    key: "log",
    value: function log(logParam) {
      var _console3;

      for (var _len3 = arguments.length, logParamRest = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
        logParamRest[_key3 - 1] = arguments[_key3];
      }

      (_console3 = console).log.apply(_console3, [logParam].concat(logParamRest, ['\n', new Error().stack.split("\n")[2]]));
    }
  }, {
    key: "warn",
    value: function warn(logParam) {
      var _console4;

      for (var _len4 = arguments.length, logParamRest = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
        logParamRest[_key4 - 1] = arguments[_key4];
      }

      (_console4 = console).log.apply(_console4, [logParam].concat(logParamRest, ['\n', new Error().stack.split("\n")[2]]));
    }
  }, {
    key: "error",
    value: function error(logParam) {
      var _console5;

      for (var _len5 = arguments.length, logParamRest = Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) {
        logParamRest[_key5 - 1] = arguments[_key5];
      }

      (_console5 = console).log.apply(_console5, [logParam].concat(logParamRest, ['\n', new Error().stack.split("\n")[2]]));
    }
  }, {
    key: "setUid",
    value: function setUid(uid) {
      WebLog.getInstance().setUid(uid);
    }
  }, {
    key: "report",
    value: function report(lv, classid, logParam) {
      for (var _len6 = arguments.length, logParamRest = Array(_len6 > 3 ? _len6 - 3 : 0), _key6 = 3; _key6 < _len6; _key6++) {
        logParamRest[_key6 - 3] = arguments[_key6];
      }

      var logElems = [logParam].concat(logParamRest);
      logElems = logElems.map(function (u) {
        if ((typeof u === "undefined" ? "undefined" : _typeof(u)) === 'object') {
          try {
            var s = JSON.stringify(u);
            u = s;
          } catch (err) {
            console.log(err);
          }
        }
        return u;
      });
      WebLog.getInstance().log(lv, classid, logElems.join(' '));
    }
  }]);

  return Logger;
}();

module.exports = Logger;

/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by aragornzhao on 2018/05/17
 * then his colleague jasonchen was to maintain this file
 * 功能：会议中的XMPP协议收发逻辑
 * 依赖：strophe的修改版本
 */

var Strophe = __webpack_require__(5).Strophe,
    $build = function $build(name, attrs) {
    return new Strophe.Builder(name, attrs);
},
    $iq = function $iq(attrs) {
    return new Strophe.Builder("iq", attrs);
},
    $msg = function $msg(attrs) {
    return new Strophe.Builder("message", attrs);
},
    $pres = function $pres(attrs) {
    return new Strophe.Builder("presence", attrs);
};
var Constants = __webpack_require__(2);
var Logger = __webpack_require__(3);

var xbtoa = void 0;
if (typeof window === 'undefined') {
    new Logger().debug('window does not exist, setting xbtoa');
    xbtoa = Strophe.btoa;
} else {
    new Logger().debug('window does exist, no need to set xbtoa');
    xbtoa = window.btoa;
}

var xatob = void 0;
if (typeof window === 'undefined') {
    new Logger().debug('window does not exist, setting xatob');
    xatob = function xatob(input) {
        /**
         * Decodes a base64 string.
         * @param {String} input The string to decode.
         */
        var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;
        // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
        do {
            enc1 = keyStr.indexOf(input.charAt(i++));
            enc2 = keyStr.indexOf(input.charAt(i++));
            enc3 = keyStr.indexOf(input.charAt(i++));
            enc4 = keyStr.indexOf(input.charAt(i++));

            chr1 = enc1 << 2 | enc2 >> 4;
            chr2 = (enc2 & 15) << 4 | enc3 >> 2;
            chr3 = (enc3 & 3) << 6 | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 !== 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 !== 64) {
                output = output + String.fromCharCode(chr3);
            }
        } while (i < input.length);
        return output;
    };
} else {
    new Logger().debug('window does exist, no need to set xatob');
    xatob = window.atob;
}

var encodeUtf8ThenB64 = function encodeUtf8ThenB64(str) {
    var r = xbtoa(unescape(encodeURIComponent(str)));
    return r;
};

var decodeB64ThenUtf8 = function decodeB64ThenUtf8(str) {
    var ret = void 0;
    try {
        var d = xatob(str);
        d = escape(d);
        ret = decodeURIComponent(d);
        return ret;
    } catch (e) {
        return '(decode str error)';
    }
};

var get_val = function get_val(itemNode, tagName) {
    var defaultRet = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';

    var elem = itemNode.getElementsByTagName(tagName);
    if (typeof elem !== 'undefined' && elem.length && elem[0].childNodes.length) {
        return elem[0].childNodes[0].nodeValue;
    }
    return defaultRet;
};

var get_attr = function get_attr(itemNode, tagName, attrName) {
    var elem = itemNode.getElementsByTagName(tagName);
    if (elem.length) {
        return elem[0].getAttribute(attrName);
    }
    return '';
};

var XmppService = function () {
    function XmppService() {
        var _this = this;

        _classCallCheck(this, XmppService);

        // console.log('XmppService constructor', (new Date()).getTime());
        this.logger = new Logger();
        //this.SERVER_URL = 'http://lumos-xmpp.com:8881/http-bind';
        //this.SERVER_URL = 'ws://203.195.137.116:8881/ws/';
        this.SERVER_URL = Constants.ConfWebSocketUrl;
        //this.SERVER_URL = 'http://10.10.88.50:7070/http-bind';
        this.connection = null;
        this.connected = false;
        this.eventListenersMap = new Map();
        this.iqInfoMap = new Map();
        this.jid = null;
        this.timeout = 10000;
        this.userLogoutFlag = false;
        this.connFailed = false;
        this.meetingPingTimer = null;

        this.createMeetingRequest = this.createMeetingRequest.bind(this);
        this.createMeetingResponseSuccess = this.createMeetingResponseSuccess.bind(this);
        this.createMeetingResponseError = this.createMeetingResponseError.bind(this);
        this.queryMeetingIdListRequest = this.queryMeetingIdListRequest.bind(this);
        this.queryMeetingIdListResponseSuccess = this.queryMeetingIdListResponseSuccess.bind(this);
        this.queryMeetingIdListResponseError = this.queryMeetingIdListResponseError.bind(this);
        this.queryMeetingItemListResponseError = this.queryMeetingItemListResponseError.bind(this);

        var bind_this = function bind_this(funcname) {
            return _this[funcname] = _this[funcname].bind(_this);
        };

        bind_this('sendIQ');
        bind_this('genErrorCallback');

        bind_this('setServerUrl');
        bind_this('connect');

        bind_this('getEventHandler');

        bind_this('userStatusPush');
        bind_this('changeHostPush');
        bind_this('notifyBeenKickedout');
        bind_this('switchMediaPermissionPush');
        bind_this('changeSettingPush');
        bind_this('notifyHansUpPush');
        bind_this('notifyHandsUpResult');

        bind_this('handsUpResponseSuccess');
        bind_this('handsUpResponseError');
        bind_this('queryMeetingItemListResponseSuccess');
        bind_this('queryMeetingItemListResponseError');

        bind_this('cancelMeetingResponseSuccess');
        bind_this('cancelMeetingResponseError');

        bind_this('modifyMeetingItemResponseSuccess');
        bind_this('modifyMeetingItemResponseError');

        bind_this('handleHandsUpResponseSuccess');
        bind_this('handleHandsUpResponseError');

        bind_this('switchMediaPermissionResponseSuccess');
        bind_this('switchMediaPermissionResponseError');

        bind_this('joinMeetingResponseSuccess');
        bind_this('joinMeetingResponseError');

        bind_this('leaveMeetingResponseSuccess');
        bind_this('leaveMeetingResponseError');

        bind_this('dissolveMeetingResponseSuccess');
        bind_this('dissolveMeetingResponseError');

        bind_this('userStatusResponseSuccess');
        bind_this('userStatusResponseError');

        bind_this('upMediaStreamResponseSuccess');
        bind_this('upMediaStreamResponseError');

        bind_this('changeHostRequest');
        bind_this('changeHostResponseSuccess');
        bind_this('changeHostResponseError');

        bind_this('dissolveMeetingRequest');
        bind_this('dissolveMeetingResponseSuccess');
        bind_this('dissolveMeetingResponseError');

        bind_this('modifyNicknameRequest');
        bind_this('setVideoLayoutRequest');
        bind_this('kickoutRequest');
    }

    /**
     * 返回单例
     */


    _createClass(XmppService, [{
        key: "setServerUrl",


        /**
         * 设置xmpp服务后台url
         * @param url
         * @returns {boolean}
         */
        value: function setServerUrl(url) {
            // console.log('xmpp setServerUrl to:', url);
            this.SERVER_URL = url;
            return true;
        }

        /**
         * xmpp 连接
         * @param jid
         * @param pwd ： token
         */

    }, {
        key: "connect",
        value: function connect(jid, pwd, wemeetAuthInfo) {
            var _this2 = this;

            // console.log('xmpp connect : this:', this);
            if (!this.connected) {
                this.connection = new Strophe.Connection(this.SERVER_URL);
                var useType = 'wemeet';
                // let useType = 'normal';
                var token_xml = pwd;
                if (useType === 'wemeet') {
                    token_xml = '<token xmlns="wemeet:auth" ';
                    token_xml += "wemeet-auth:app_id=\"" + wemeetAuthInfo.app_id + "\" ";
                    token_xml += "wemeet-auth:device_id=\"" + wemeetAuthInfo.device_id + "\" ";
                    token_xml += "wemeet-auth:network_type=\"" + wemeetAuthInfo.network_type + "\" ";
                    token_xml += "wemeet-auth:app_version=\"" + wemeetAuthInfo.app_version + "\" ";
                    token_xml += "wemeet-auth:sdk_version=\"" + wemeetAuthInfo.sdk_version + "\" ";
                    token_xml += "wemeet-auth:auth_type=\"" + wemeetAuthInfo.auth_type + "\">";
                    token_xml += xbtoa(pwd) + '</token>';
                }
                this.connection.connect(jid, token_xml, function (status, condition) {
                    var login_cb = _this2.getEventHandler('login');
                    if (status === Strophe.Status.CONNFAIL) {
                        console.log("connection failed:", condition);
                        _this2.jid = null;
                        _this2.connFailed = true;
                        var connfail_cb = _this2.getEventHandler('connfailed');
                        connfail_cb(true, { 'code': 'CONNFAIL', 'msg': 'disconnected', 'data': condition });
                    } else if (status === Strophe.Status.AUTHFAIL) {
                        console.log("authentication failed:", condition);
                        login_cb(false, { 'code': 'AUTHFAIL', 'msg': 'authentication failed' });
                    } else if (status === Strophe.Status.DISCONNECTED) {
                        console.log("disconnected:", condition);
                        _this2.jid = null;
                        if ((typeof condition === "undefined" ? "undefined" : _typeof(condition)) === 'object') {
                            console.log('condition:', JSON.stringify(condition));
                        }
                        if (_this2.meetingPingTimer) {
                            clearInterval(_this2.meetingPingTimer);
                            _this2.meetingPingTimer = null;
                        }
                        _this2.connected = false;
                        var logout_cb = _this2.getEventHandler('logout');
                        var retData = {
                            msg: 'disconnected',
                            code: 'DISCONNECTED',
                            ecode: 99900, // 99900 is a default code representing `unknown`
                            condition: condition
                        };
                        if (typeof condition !== 'undefined' && typeof condition.code !== 'undefined') {
                            retData.ecode = condition.code;
                        } else if (_this2.connFailed) {
                            retData.ecode = 98888; // 98888 for CONNFAIL
                            _this2.connFailed = false;
                        }
                        logout_cb(_this2.userLogoutFlag, retData);
                        _this2.userLogoutFlag = false;
                    } else if (status === Strophe.Status.CONNECTED) {
                        console.log("connect success:", condition);
                        _this2.connected = true;

                        // S2C的报文在此处理，其他的IQ响应交给自身设置的回调处理
                        _this2.connection.addHandler(function (msg) {
                            var msg_type = msg.getAttribute('type');
                            if (msg_type === 'result') {
                                if (msg.childNodes.length > 0) {
                                    var main_node = msg.childNodes[0];
                                    if (main_node.getAttribute('xmlns') === "tencent:wemeet:push") {
                                        var protocol_type = main_node.nodeName;
                                        console.log('push!!!---protocol_type:', protocol_type);
                                        _this2.serverToClientMsgParser(msg, protocol_type);
                                    }
                                }
                            }
                            return true;
                        }, null, 'iq', null, null, null);

                        // 要先发送一个<presence>给服务器（initial presence）
                        _this2.connection.send($pres().tree());

                        _this2.jid = jid;

                        setTimeout(function () {
                            login_cb(true, { 'code': 'CONNECTED', 'msg': 'connect success' });
                        }, 10);
                    }
                });
            }
        }
    }, {
        key: "disconnect",
        value: function disconnect() {
            this.logger.info("xmpp disconnect called");
            this.logger.info("this.connected: " + this.connected);
            if (this.connected) {
                this.userLogoutFlag = true;
                this.logger.info('xmpp calling connection disconnect');
                this.connection.disconnect('libWeMeet.xmpp_service');
            }
            this.connected = false;
        }

        /**
         * 注册回调函数响应
         * @param event_key  事件名称
         * @param callBackFun 回调函数对象
         * @returns {boolean}
         */

    }, {
        key: "registerEventHandler",
        value: function registerEventHandler(event_key, callBackFun) {
            if (typeof callBackFun === "function") {

                var arrcb = this.eventListenersMap.get(event_key);
                if (arrcb === undefined) {
                    arrcb = [];
                }
                arrcb.push(callBackFun);
                this.logger.debug("MUC.registerEventHandler", event_key, arrcb.length);
                this.eventListenersMap.set(event_key, arrcb);

                // this.eventListenersMap.set(event_key, callBackFun);
                return true;
            }
            return false;
        }

        /**
         * 获取回调函数
         * @param event_key
         * @returns {function}
         */

    }, {
        key: "getEventHandler",
        value: function getEventHandler(event_key) {
            // let cb = this.eventListenersMap.get(event_key);

            var arrcb = this.eventListenersMap.get(event_key);
            if (arrcb === undefined) {
                console.warn('xmpp service getEventHandler returning an empty handler function for event_key', event_key);
                return function () {};
            }

            // const caller; // can we use const here?
            var caller = function caller(flag, data) {
                var _iteratorNormalCompletion = true;
                var _didIteratorError = false;
                var _iteratorError = undefined;

                try {
                    for (var _iterator = arrcb[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                        var cb = _step.value;

                        cb(flag, data);
                    }
                } catch (err) {
                    _didIteratorError = true;
                    _iteratorError = err;
                } finally {
                    try {
                        if (!_iteratorNormalCompletion && _iterator.return) {
                            _iterator.return();
                        }
                    } finally {
                        if (_didIteratorError) {
                            throw _iteratorError;
                        }
                    }
                }
            };

            return caller;

            // if (typeof(cb) === 'undefined') {
            //     console.warn('xmpp service getEventHandler returning an empty handler function for event_key', event_key);
            //     cb = function () {};
            // }

            // return cb;
        }

        /**
         * 发生信息报表方法
         * @param msg: xml 报文
         */

    }, {
        key: "send",
        value: function send(msg) {
            if (this.connected) {
                this.logger.info(msg);
                this.connection.send(msg);
            } else {
                console.log('please build connection first');
            }
        }

        /**
         * 发送iq消息
         * @param msg 消息结构
         * @param successCallBack  成功回调
         * @param errorCallBack 失败回调
         */

    }, {
        key: "sendIQ",
        value: function sendIQ(msg, successCallBack, errorCallBack) {
            if (this.connected) {
                // this.logger.info(msg.tree());
                this.connection.sendIQ(msg, successCallBack, errorCallBack, this.timeout);
            } else {
                console.log('please build connection first');
                if (typeof errorCallBack === 'function') {
                    errorCallBack({
                        isNOTXml: true,
                        code: '0',
                        msg: 'please build connection first'
                    });
                }
            }
        }
    }, {
        key: "genErrorCallback",
        value: function genErrorCallback(msg, handler_name) {
            var _this3 = this;

            return function () {
                var cb = _this3.getEventHandler(handler_name);
                if (msg) {
                    if (msg.hasOwnProperty('isNOTXml') && msg.isNOTXml) {
                        cb(false, msg);
                    } else {
                        var el = msg.getElementsByTagName("error")[0];
                        cb(false, {
                            "msg": el.childNodes[0].nodeValue,
                            "code": el.getAttribute("code")
                        });
                    }
                } else {
                    cb(false, null); // indicating timeout
                }
            };
        }

        /**
         * 获取连接状态
         * @returns {boolean} ： true 已连接, false 未连接
         */

    }, {
        key: "getConnectState",
        value: function getConnectState() {
            return this.connected;
        }
    }, {
        key: "serverToClientMsgParser",
        value: function serverToClientMsgParser(msg, protocol_type) {
            var protoHandlers = {
                "user_status": "userStatusPush",
                "change_host": "changeHostPush",
                "switch_media_permission": "switchMediaPermissionPush",
                "change_setting": "changeSettingPush",
                "notify_hands_up": "notifyHansUpPush",
                "notify_hands_up_result": "notifyHandsUpResult",
                "kick_out": "notifyBeenKickedout",
                "modify": "notifyMeetingModified",
                "schedule": "notifySchedule",
                "meeting_item_update": "notifyMeetingItemUpdate"
            };
            var handler = protoHandlers[protocol_type];
            if (typeof handler !== 'undefined') {
                this[handler](msg);
            }
        }
    }, {
        key: "userStatusPush",
        value: function userStatusPush(msg) {
            console.log('on Push user_status, msg:', msg);
            var mainNode = msg.getElementsByTagName('user_status')[0];
            var opType = parseInt(mainNode.getElementsByTagName('type')[0].childNodes[0].nodeValue);
            var meeting_id = mainNode.getElementsByTagName('meeting_id')[0].childNodes[0].nodeValue;
            var item_list = mainNode.getElementsByTagName('list')[0].childNodes;
            var data = { user_list: [], meeting_id: meeting_id };
            for (var i = 0; i < item_list.length; i++) {
                var itemNode = item_list[i];
                var user = {
                    nickname: decodeB64ThenUtf8(get_val(itemNode, 'nickname')),
                    is_creator: get_val(itemNode, 'is_creator'),
                    is_host: get_val(itemNode, 'is_host'),
                    id: {
                        uid: itemNode.getElementsByTagName('id')[0].getAttribute('app_uid'),
                        app_id: itemNode.getElementsByTagName('id')[0].getAttribute('app_id'),
                        instance_id: itemNode.getElementsByTagName('id')[0].getAttribute('instance_id'),
                        av_uid: get_val(itemNode, 'av_uid')
                    },
                    video_on: get_val(itemNode, 'up_video_on'),
                    audio_on: get_val(itemNode, 'up_audio_on'),
                    share_on: get_val(itemNode, 'up_share_on'),
                    video_reason: get_attr(itemNode, 'up_video_on', 'reason'),
                    audio_reason: get_attr(itemNode, 'up_audio_on', 'reason'),
                    share_reason: get_attr(itemNode, 'up_share_on', 'reason'),
                    handsup: get_val(itemNode, 'handsup'),
                    user_type: get_val(itemNode, 'user_type')
                };

                data.user_list.push(user);
            }
            console.log('  data:', data);

            this.logger.debug('xmpp userStatusPush opType:', opType);

            var eventName = void 0;
            switch (opType) {
                case Constants.UserState.JOIN:
                    eventName = 'user_join';
                    break;
                case Constants.UserState.LEAVE:
                    eventName = 'user_leave';
                    break;
                case Constants.UserState.UPDATE:
                    eventName = 'user_update';
                    break;
                case Constants.UserState.KICKED:
                    eventName = 'user_kicked';
                    break;
            }
            var cb = this.getEventHandler(eventName);
            cb(true, data);
        }
    }, {
        key: "changeHostPush",
        value: function changeHostPush(msg) {
            console.log('on Push change_host, msg:', msg);
            var mainNode = msg.getElementsByTagName('change_host')[0];
            var meetingId = mainNode.getElementsByTagName('meeting_id')[0].childNodes[0].nodeValue;
            var hostNode = mainNode.getElementsByTagName('id')[0];
            var host = {
                uid: hostNode.getAttribute('app_uid'),
                app_id: hostNode.getAttribute('app_id'),
                instance_id: hostNode.getAttribute('instance_id')
            };
            console.log('  host:', host);
            var cb = this.getEventHandler("change_host_push");
            cb(true, { meeting_id: meetingId, host: host });
        }
    }, {
        key: "switchMediaPermissionPush",
        value: function switchMediaPermissionPush(msg) {
            this.logger.log('on Push switch MediaPermission, msg:', msg);
            var mainNode = msg.getElementsByTagName('switch_media_permission')[0];
            var data = {
                op_type: get_val(mainNode, 'type'),
                is_grant: get_val(mainNode, 'is_grant'),
                all_user: get_val(mainNode, 'all_user')
            };
            console.log('  data:', data);
            var cb = this.getEventHandler("switch_media_permission_push");
            cb(true, data);
        }
    }, {
        key: "changeSettingPush",
        value: function changeSettingPush(msg) {
            console.log('on Push change_setting, msg:', msg);
            var mainNode = msg.getElementsByTagName('change_setting')[0];
            var data = {
                op_type: mainNode.getElementsByTagName('type')[0].childNodes[0].nodeValue,
                user: {
                    uid: mainNode.getElementsByTagName('attach')[0].getElementsByTagName('id')[0].getAttribute('uid'),
                    app_id: mainNode.getElementsByTagName('attach')[0].getElementsByTagName('id')[0].getAttribute('app_id'),
                    instance_id: mainNode.getElementsByTagName('attach')[0].getElementsByTagName('id')[0].getAttribute('instance_id')
                }
            };
            console.log('  data:', data);
            var cb = this.getEventHandler("on_spot_light_video_push");
            cb(true, data);
        }

        // notify every user someone had made the 'handsup' action.

    }, {
        key: "notifyHansUpPush",
        value: function notifyHansUpPush(msg) {
            console.log('on Push notify_hands_up, msg:', msg);
            var mainNode = msg.getElementsByTagName('notify_hands_up')[0];
            var permissionList = [];
            var pl = mainNode.getElementsByTagName('permission_list');
            if (pl && pl.length) {
                var ps = pl[0].getElementsByTagName('permission');
                if (ps && ps.length) {
                    for (var i = 0; i < ps.length; ++i) {
                        var pn = ps[i];
                        if (pn) {
                            permissionList.push(parseInt(pn.getAttribute('type')));
                        }
                    }
                }
            }
            var data = {
                user: {
                    uid: mainNode.getElementsByTagName('id')[0].getAttribute('uid'),
                    app_id: mainNode.getElementsByTagName('id')[0].getAttribute('app_id'),
                    instance_id: mainNode.getElementsByTagName('id')[0].getAttribute('instance_id')
                },
                permission: permissionList
            };
            console.log('  data:', data);
            var cb = this.getEventHandler("notify_hands_up_push");
            cb(true, data);
        }

        // notify the user that made 'handsup' action what the host dealt with it.

    }, {
        key: "notifyHandsUpResult",
        value: function notifyHandsUpResult(msg) {
            this.logger.debug('xmpp notifyHandsUpResult msg:', msg);
            var data = {
                permissionList: []
            };
            var mainNode = msg.getElementsByTagName('notify_hands_up_result')[0];
            var permissionListNode = mainNode.getElementsByTagName('permission_list')[0];
            var permissionNodes = permissionListNode.getElementsByTagName('permission');
            for (var i = 0; i < permissionNodes.length; ++i) {
                var pNode = permissionNodes[i];
                data.permissionList.push({
                    type: pNode.getAttribute('type'),
                    is_grant: pNode.getAttribute('is_grant')
                });
            }
            var cb = this.getEventHandler("notify_hands_up_result");
            cb(true, data);
        }
    }, {
        key: "notifyBeenKickedout",
        value: function notifyBeenKickedout(msg) {
            this.logger.debug('notifyBeenKickedout, msg:', msg);
            var mainNode = msg.getElementsByTagName('kick_out')[0];
            var data = {};

            data.meetingId = get_val(mainNode, 'meeting_id');
            data.kicker = {
                uid: get_attr(mainNode, 'kicker', 'app_uid'),
                app_id: get_attr(mainNode, 'kicker', 'app_id'),
                instance_id: get_attr(mainNode, 'kicker', 'instance_id')
            };
            data.reason = get_val(mainNode, 'reason');
            data.reasonCode = get_attr(mainNode, 'reason', 'code');

            var cb = this.getEventHandler("kicked_out");
            cb(true, data);
        }
    }, {
        key: "notifyMeetingModified",
        value: function notifyMeetingModified(msg) {
            this.logger.debug('notifyMeetingModified, msg:', msg);
            var mainNode = msg.getElementsByTagName('modify')[0];
            var data = {};
            data.meeting_id = get_val(mainNode, 'meeting_id');
            data.subject = decodeB64ThenUtf8(get_val(mainNode, 'subject', null));
            data.begin_time = get_val(mainNode, 'begin_time', null);
            data.end_time = get_val(mainNode, 'end_time', null);
            data.password = get_val(mainNode, 'password', null);
            data.location = decodeB64ThenUtf8(get_val(mainNode, 'location', null));
            data.custom_buffer = decodeB64ThenUtf8(get_val(mainNode, 'custom_buffer'));

            // 以下的解析可参考 _parse_meeting_item
            // 一期的需求以下不需要解析

            // compound
            // data.host = get_val(mainNode, 'xxxxx', null);

            // list compound
            // data.invite_list = get_val(mainNode, 'xxxxx', null);

            var cb = this.getEventHandler("meeting_modified");
            cb(true, data);
        }
    }, {
        key: "notifySchedule",
        value: function notifySchedule(msg) {
            var mainNode = msg.getElementsByTagName('schedule')[0];
            var data = {};
            data.meeting_id = get_val(mainNode, 'meeting_id');
            data.meeting_code = get_val(mainNode, 'meeting_code');
            data.meeting_state = get_val(mainNode, 'meeting_state');
            data.begin_time = get_val(mainNode, 'begin_time');
            data.end_time = get_val(mainNode, 'end_time');
            data.last_modify_time = get_val(mainNode, 'last_modify_time');
            data.actual_begin_time = get_val(mainNode, 'actual_begin_time');
            data.actual_end_time = get_val(mainNode, 'actual_end_time');
            data.subject = decodeB64ThenUtf8(get_val(mainNode, 'subject', null));
            data.custom_buffer = decodeB64ThenUtf8(get_val(mainNode, 'custom_buffer'));

            var cb = this.getEventHandler("notify_schedule");
            cb(true, data);
        }
    }, {
        key: "notifyMeetingItemUpdate",
        value: function notifyMeetingItemUpdate(msg) {
            var mainNode = msg.getElementsByTagName('meeting_item_update')[0];
            var data = {};
            data.meeting_id = get_val(mainNode, 'meeting_id');
            data.meeting_code = get_val(mainNode, 'meeting_code');
            data.meeting_state = get_val(mainNode, 'meeting_state');
            data.begin_time = get_val(mainNode, 'begin_time');
            data.end_time = get_val(mainNode, 'end_time');
            data.last_modify_time = get_val(mainNode, 'last_modify_time');
            data.actual_begin_time = get_val(mainNode, 'actual_begin_time');
            data.actual_end_time = get_val(mainNode, 'actual_end_time');
            data.subject = decodeB64ThenUtf8(get_val(mainNode, 'subject', null));
            data.custom_buffer = decodeB64ThenUtf8(get_val(mainNode, 'custom_buffer'));

            var cb = this.getEventHandler("notify_meeting_item_update");
            cb(true, data);
        }

        /* 发送报文封装*/

    }, {
        key: "userStatusRequest",
        value: function userStatusRequest(status_params) {
            var iq = $iq({
                type: 'set'
            }).c("user_status", { xmlns: "tencent:wemeet:meeting_ctrl" }).c("meeting_id").t(status_params.meeting_id).up().c("type").t(status_params.type).up();

            // cnt for: c() and t()
            var cnt = function cnt(paramName) {
                if (status_params.hasOwnProperty(paramName)) {
                    iq.c(paramName).t(status_params[paramName]).up();
                }
            };

            // c() set attr and t()
            var cant = function cant(paramName, numReason) {
                if (status_params.hasOwnProperty(paramName)) {
                    iq.c('up_' + paramName, { reason: numReason.toString() }).t(status_params[paramName]).up();
                }
            };

            if (status_params.hasOwnProperty('nickname')) {
                status_params['nickname'] = encodeUtf8ThenB64(status_params['nickname']);
            }

            ['nickname'].map(cnt);
            cant('video_on', status_params.video_reason);
            cant('audio_on', status_params.audio_reason);
            cant('share_on', status_params.share_reason);

            this.sendIQ(iq, this.userStatusResponseSuccess, this.userStatusResponseError);
        }
    }, {
        key: "userStatusResponseSuccess",
        value: function userStatusResponseSuccess(msg) {
            var cb = this.getEventHandler('user_status');
            cb(true, { "msg": msg });
        }
    }, {
        key: "userStatusResponseError",
        value: function userStatusResponseError(msg) {
            this.genErrorCallback(msg, 'user_status')();
        }

        /**
         * 主持人身份变更
         * @param account 即将成为主持人的账号信息
         */

    }, {
        key: "changeHostRequest",
        value: function changeHostRequest(meeting_id, account) {
            var iq = $iq({
                type: 'set'
            }).c("change_host", { xmlns: "tencent:wemeet:meeting_ctrl" }).c("meeting_id").t(meeting_id).up().c("id", { app_uid: account.uid, app_id: account.app_id, instance_id: account.instance_id }).up();
            this.sendIQ(iq, this.changeHostResponseSuccess, this.changeHostResponseError);
        }
    }, {
        key: "changeHostResponseSuccess",
        value: function changeHostResponseSuccess(msg) {
            var cb = this.getEventHandler('change_host');
            cb(true, { "msg": "change host success" });
        }
    }, {
        key: "changeHostResponseError",
        value: function changeHostResponseError(msg) {
            this.genErrorCallback(msg, 'change_host')();
        }

        /**
         * 音视频流上行权限开关转换
         * @param account  被操作的用户
         * @param meeting_id 会议的id
         * @param op_type 操作类型 1：up_audio 2: up_video  3: up_share_screen
         * @param is_enable 赋予/取消相关权限
         * @param is_all_users 是否对全员操作 |如果这里设置true，则以all_user为准,uid不生效|
         */

    }, {
        key: "switchMediaPermissionRequest",
        value: function switchMediaPermissionRequest(account, meeting_id, op_type, is_enable, is_all_users) {
            var iq = $iq({
                type: 'set'
            }).c("switch_media_permission", { xmlns: "tencent:wemeet:meeting_ctrl" }).c("meeting_id").t(meeting_id).up().c("id", { app_uid: account.uid, app_id: account.app_id, instance_id: account.instance_id }).up().c("type").t(op_type).up().c("is_grant").t(is_enable).up().c("all_user").t(is_all_users).up();
            this.sendIQ(iq, this.switchMediaPermissionResponseSuccess, this.switchMediaPermissionResponseError);
            var msg_type = null;
            if (is_all_users) {
                switch (op_type) {
                    case Constants.MediaType.AUDIO:
                        msg_type = 'mute_all_audio';
                        break;
                    case Constants.MediaType.VIDEO:
                        msg_type = 'mute_all_video';
                        break;
                }
            } else {
                switch (op_type) {
                    case Constants.MediaType.AUDIO:
                        msg_type = 'mute_audio';
                        break;
                    case Constants.MediaType.VIDEO:
                        msg_type = 'mute_video';
                        break;
                }
            }
            // console.log('switchMediaPermissionRequest send iq is:', iq);
            // console.log('iq.nodeTree.attributes:', iq.nodeTree.attributes);
            // console.log('iq.nodeTree.attributes(JSON):', JSON.stringify(iq.nodeTree.attributes));
            // console.log('iq.nodeTree.attributes[2].nodeValue:', iq.nodeTree.attributes[2].nodeValue);
            // this.iqInfoMap.set(iq.nodeTree.id, msg_type);
            this.iqInfoMap.set(iq.nodeTree.attributes[2].nodeValue, msg_type);
        }
    }, {
        key: "switchMediaPermissionResponseSuccess",
        value: function switchMediaPermissionResponseSuccess(msg) {
            var id = msg.getAttribute('id');
            // console.log('switchMediaPermissionResponseError: msg id is:', id);
            // console.log('switchMediaPermissionResponseError: this.iqInfoMap is:', this.iqInfoMap);
            var msg_type = this.iqInfoMap.get(id);
            var cb = this.getEventHandler(msg_type);
            cb(true, { "msg": msg });
            this.iqInfoMap.delete(id);
        }
    }, {
        key: "switchMediaPermissionResponseError",
        value: function switchMediaPermissionResponseError(msg) {
            // not a perfect way, but should be enough in practice
            if (msg === null) {
                var _iteratorNormalCompletion2 = true;
                var _didIteratorError2 = false;
                var _iteratorError2 = undefined;

                try {
                    for (var _iterator2 = this.iqInfoMap[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                        var _ref = _step2.value;

                        var _ref2 = _slicedToArray(_ref, 2);

                        var key = _ref2[0];
                        var val = _ref2[1];

                        this.getEventHandler(val)(false, null);
                    }
                } catch (err) {
                    _didIteratorError2 = true;
                    _iteratorError2 = err;
                } finally {
                    try {
                        if (!_iteratorNormalCompletion2 && _iterator2.return) {
                            _iterator2.return();
                        }
                    } finally {
                        if (_didIteratorError2) {
                            throw _iteratorError2;
                        }
                    }
                }

                this.iqInfoMap.clear();
                return;
            }
            var id = msg.getAttribute('id');
            // console.log('switchMediaPermissionResponseError: msg id is:', id);
            // console.log('switchMediaPermissionResponseError: this.iqInfoMap is:', this.iqInfoMap);
            var msg_type = this.iqInfoMap.get(id);
            var cb = this.getEventHandler(msg_type);
            cb(false, { "msg": msg.getElementsByTagName("error")[0].childNodes[0].nodeValue });
            this.iqInfoMap.delete(id);
        }

        /**
         * 普通用户请求音视频上行
         * @param meeting_id
         * @param media_type 1：up_audio 2: up_video  3: up_share_screen
         */

    }, {
        key: "upMediaStreamRequest",
        value: function upMediaStreamRequest(meeting_id, media_type) {
            var iq = $iq({
                type: 'set'
            }).c("request_up_stream", { xmlns: "tencent:wemeet:media_ctrl" }).c("meeting_id").t(meeting_id).up().c("permission_list").c("permission", { type: media_type }).up().up();
            this.sendIQ(iq, this.upMediaStreamResponseSuccess, this.upMediaStreamResponseError);
        }
    }, {
        key: "upMediaStreamResponseSuccess",
        value: function upMediaStreamResponseSuccess(msg) {
            var cb = this.getEventHandler('up_media_stream');
            var xmlstr = '';
            try {
                xmlstr = new XMLSerializer().serializeToString(msg);
            } catch (e) {
                // do nothing.
            }
            this.logger.debug('xmpp upMediaStreamResponseSuccess msg:', msg, '\nmsg(str):', xmlstr);

            var mainNode = msg.getElementsByTagName('request_up_stream')[0];
            var meetingId = get_val(mainNode, 'meeting_id');
            var permissionList = [];
            var pl = mainNode.getElementsByTagName('permission_list');
            if (pl && pl.length) {
                var ps = pl[0].getElementsByTagName('permission');
                if (ps && ps.length) {
                    for (var i = 0; i < ps.length; ++i) {
                        var pn = ps[i];
                        if (pn) {
                            permissionList.push({
                                type: parseInt(pn.getAttribute('type')),
                                is_grant: parseInt(pn.getAttribute('is_grant'))
                            });
                        }
                    }
                }
            }

            var data = {
                meeting_id: meetingId,
                permission_list: permissionList
            };

            cb(true, data);
        }
    }, {
        key: "upMediaStreamResponseError",
        value: function upMediaStreamResponseError(msg) {
            this.genErrorCallback(msg, 'up_media_stream')();
        }

        /**
         * 普通用户上行/取消上行后向server同步状态
         * @param account 用户信息
         * @param stream_type 同步状态的类型 | 1:audio 2:video 3:share_screen|
         * @param is_enable 1：开，0：关
         */

    }, {
        key: "notifyMediaStatusRequest",
        value: function notifyMediaStatusRequest(account, stream_type, is_enable) {
            var iq = $iq({
                type: 'set'
            }).c("notify_media_status", { xmlns: "tencent:wemeet:media_ctrl" }).c("type").t(stream_type).up().c("on").t(is_enable).up().c("id", { uid: account.uid, app_id: account.app_id, instance_id: account.app_id }).up();
            this.sendIQ(iq, this.notifyMediaStatusResponseSuccess, this.notifyMediaStatusResponseError);
        }
    }, {
        key: "notifyMediaStatusResponseSuccess",
        value: function notifyMediaStatusResponseSuccess(msg) {
            var cb = this.getEventHandler('notify_media_status');
            cb(true, { "msg": "up_media_stream success" });
        }
    }, {
        key: "notifyMediaStatusResponseError",
        value: function notifyMediaStatusResponseError(msg) {
            this.genErrorCallback(msg, 'notify_media_status')();
        }

        /**
         * 设置大画面显示的user_id
         * @param account 被操作的用户
         * @param op_type 1：设置成员当前大画面的显示
         */

    }, {
        key: "changeSettingRequest",
        value: function changeSettingRequest(account, op_type) {
            var iq = $iq({
                type: 'set'
            }).c("change_setting", { xmlns: "tencent:wemeet:meeting_ctrl" }).c("type").t(op_type).up().c("attach").c("id", { uid: account.uid, app_id: account.app_id, instance_id: account.app_id }).up();
            this.sendIQ(iq, this.changeSettingResponseSuccess, this.changeSettingResponseRequest);
        }
    }, {
        key: "changeSettingResponseSuccess",
        value: function changeSettingResponseSuccess() {
            var cb = this.getEventHandler('change_setting');
            cb(true, { "msg": "change_setting success" });
        }
    }, {
        key: "changeSettingResponseRequest",
        value: function changeSettingResponseRequest() {
            this.genErrorCallback(msg, 'change_setting')();
        }

        /**
         * 举手请求
         * @param meetingId 会议id
         * @param typeVal 1:举手 0:放下手
         * @param permission 举手时需要请求的权限类型，可以多个 1:audio 2:video 3:share_screen
         */

    }, {
        key: "handsUpRequest",
        value: function handsUpRequest(meetingId, typeVal, permissionList) {
            var iq = $iq({
                type: 'set'
            }).c("handsup", { xmlns: "tencent:wemeet:meeting_ctrl" }).c("type", typeVal.toString()).up().c("meeting_id", meetingId).up().c("permission_list");
            var _iteratorNormalCompletion3 = true;
            var _didIteratorError3 = false;
            var _iteratorError3 = undefined;

            try {
                for (var _iterator3 = permissionList[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
                    var p = _step3.value;

                    iq.c("permission", { type: p }).up();
                }
            } catch (err) {
                _didIteratorError3 = true;
                _iteratorError3 = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion3 && _iterator3.return) {
                        _iterator3.return();
                    }
                } finally {
                    if (_didIteratorError3) {
                        throw _iteratorError3;
                    }
                }
            }

            this.sendIQ(iq, this.handsUpResponseSuccess, this.handsUpResponseError);
        }
    }, {
        key: "handsUpResponseSuccess",
        value: function handsUpResponseSuccess(msg) {
            console.log('xmpp service handsUpResponseSuccess');
            var cb = this.getEventHandler('hands_up');
            cb(true, { "msg": "hands_up success" });
        }
    }, {
        key: "handsUpResponseError",
        value: function handsUpResponseError(msg) {
            this.genErrorCallback(msg, 'hands_up')();
        }

        /**
         * 主持人管理举手 处理哪个用户的举手操作
         * @param meeting_id
         * @param account
         * @param req_type 1,2,3
         * @param is_grant 0：拒绝用户举手操作 1：同意用户举手操作
         */

    }, {
        key: "handleHandsUpRequest",
        value: function handleHandsUpRequest(meeting_id, account, req_type, is_grant) {
            var iq = $iq({
                type: 'set'
            }).c("handle_handsup", { xmlns: "tencent:wemeet:meeting_ctrl" }).c("meeting_id").t(meeting_id).up().c("id", { app_uid: account.uid, app_id: account.app_id, instance_id: account.instance_id }).up().c("permission_list").c("permission", { type: req_type, is_grant: is_grant }).up().up();
            this.sendIQ(iq, this.handleHandsUpResponseSuccess, this.handleHandsUpResponseError);
        }
    }, {
        key: "handleHandsUpResponseSuccess",
        value: function handleHandsUpResponseSuccess(msg) {
            var cb = this.getEventHandler('handle_hands_up');
            cb(true, _defineProperty({ "msg": "handle_hands_up success, msg:" }, "msg", msg));
        }
    }, {
        key: "handleHandsUpResponseError",
        value: function handleHandsUpResponseError(msg) {
            this.genErrorCallback(msg, 'handle_hands_up')();
        }

        /**
         * 创建会议
         * @param confParams
         * subject | 会议主题
         * begin_time| 会议开始时间
         * end_time|会议结束时间
         * password|加入会议密码
         * location|会议地点
         * host | 主持人
         * custom_buffer|预留字段
         * invite_list array
         *      app_uid|与会成员ID
         *      app_id|与会成员appid
         */

    }, {
        key: "createMeetingRequest",
        value: function createMeetingRequest(confParams) {
            var iq = $iq({
                type: 'set'
            }).c("schedule", { xmlns: "tencent:wemeet:meeting" }).c("host", { app_id: confParams.host.app_id, app_uid: confParams.host.app_uid }).up();

            if (confParams.hasOwnProperty('subject')) {
                confParams['subject'] = encodeUtf8ThenB64(confParams['subject']);
            }
            if (confParams.hasOwnProperty('location')) {
                confParams['location'] = encodeUtf8ThenB64(confParams['location']);
            }

            if (confParams.hasOwnProperty('is_quick_meeting')) {
                confParams['create_type'] = confParams['is_quick_meeting'];
            } else {
                confParams['create_type'] = "0";
            }

            // cnt for: c() and t()
            var cnt = function cnt(paramName) {
                if (confParams.hasOwnProperty(paramName)) {
                    iq.c(paramName).t(confParams[paramName]).up();
                }
            };

            ["subject", "begin_time", "end_time", "location", "custom_buffer", "password", "create_type"].map(cnt);

            iq.c("invite_list");

            for (var i = 0; i < confParams.invite_list.length; i++) {
                var item = confParams.invite_list[i];
                iq.c('member', { app_uid: item.app_uid, app_id: item.app_id }).up();
            }

            this.sendIQ(iq, this.createMeetingResponseSuccess, this.createMeetingResponseError);
        }
    }, {
        key: "createMeetingResponseSuccess",
        value: function createMeetingResponseSuccess(msg) {
            var mainNode = msg.getElementsByTagName('schedule')[0];
            var itemNode = mainNode;
            var meeting_id = get_val(itemNode, 'meeting_id');
            var url = decodeB64ThenUtf8(get_val(itemNode, 'url'));
            var meeting_code = get_val(itemNode, 'meeting_code');
            var begin_time = get_val(itemNode, 'begin_time');
            var end_time = get_val(itemNode, 'end_time');
            var password = get_val(itemNode, 'password');
            var is_quick_meeting = get_val(itemNode, 'create_type');
            var pstn_phone = get_val(itemNode, 'pstn_phone');
            var data = {
                meeting_id: meeting_id,
                meeting_code: meeting_code,
                url: url,
                begin_time: begin_time,
                end_time: end_time,
                password: password,
                is_quick_meeting: is_quick_meeting,
                pstn_phone: pstn_phone,
                pstn_code: itemNode.getElementsByTagName('pstn_code')[0].childNodes[0].nodeValue,
                host: {
                    app_id: itemNode.getElementsByTagName('host')[0].getAttribute("app_id"),
                    app_uid: itemNode.getElementsByTagName('host')[0].getAttribute("app_uid")
                },
                subject: decodeB64ThenUtf8(get_val(itemNode, 'subject')),
                location: decodeB64ThenUtf8(get_val(itemNode, 'location')),
                invite_list: []
            };

            // ** 一期没有invite **
            // let invite_list_node = itemNode.getElementsByTagName('invite_list');
            // for(let i=0; i<invite_list_node.childNodes.length; i++){
            //     let member_node = invite_list_node.childNodes[i];
            //     data.invite_list.push({
            //         app_id: member_node.getAttribute("app_id"),
            //         app_uid: member_node.getAttribute("app_uid")
            //     });
            // }

            var cb = this.getEventHandler('create_meeting');
            cb(true, data);
        }
    }, {
        key: "createMeetingResponseError",
        value: function createMeetingResponseError(msg) {
            this.genErrorCallback(msg, 'create_meeting')();
        }

        /**
         * 查询会议ID列表
         * @param queryParams
         *      begin_time | 开始时间,	缺省或为0时不限定开始时间
         *      end_time | 	结束时间,缺省或为0时不限定结束时间
         *      creator_uid | 会议创建者的app_uid,缺省时不限定该条件。 如果带此字段，则只查询该用户创建的会议
         *      is_creator | 本人为创建者,缺省时不限定该条件。如果为true，则只查询该用户创建的会议，如果为false，则不查询该用户创建的会议。
         *      is_invitee| 本人为被邀请者,缺省时不限定该条件。如果为true，则只查询邀请该用户的会议，如果为false，则不查询邀请该用户的会议。
         */

    }, {
        key: "queryMeetingIdListRequest",
        value: function queryMeetingIdListRequest(queryParams) {
            var iq = $iq({
                type: 'get'
            }).c("query_meeting_id_list", { xmlns: "tencent:wemeet:meeting" }).c("begin_time").t(queryParams.begin_time).up().c("end_time").t(queryParams.end_time).up().c("creator_uid").t(queryParams.creator_uid).up().c("is_creator").t(queryParams.is_creator).up().c("is_invitee").t(queryParams.is_invitee).up().c("meeting_id").t(queryParams.meeting_id).up();
            this.sendIQ(iq, this.queryMeetingIdListResponseSuccess, this.queryMeetingIdListResponseError);
        }
    }, {
        key: "queryMeetingIdListResponseSuccess",
        value: function queryMeetingIdListResponseSuccess(msg) {
            data = { meeting_id_list: [] };
            var mainNode = msg.getElementsByTagName('query_meeting_id_list')[0];
            var itemNode = mainNode.getElementsByTagName('meeting_id_list')[0];
            for (var i = 0; i < itemNode.childNodes.length; i++) {
                var valueNode = itemNode.childNodes[i];
                data.meeting_id_list.push(valueNode[0].childNodes[0].nodeValue);
            }

            var cb = this.getEventHandler('query_meeting_id_list');
            cb(true, data);
        }
    }, {
        key: "queryMeetingIdListResponseError",
        value: function queryMeetingIdListResponseError(msg) {
            this.genErrorCallback(msg, 'query_meeting_id_list')();
        }

        /**
         * 查询会议ID列表
         * @param queryParams
         */

    }, {
        key: "queryMeetingItemListRequest",
        value: function queryMeetingItemListRequest(queryParams) {
            var iq = $iq({
                type: 'get'
            }).c("query_meeting_item_list", { xmlns: "tencent:wemeet:meeting" }).c("meeting_id").t(queryParams.meeting_id).up();

            if (queryParams.hasOwnProperty('begin_time')) {
                iq.c("begin_time").t(queryParams.begin_time).up();
            }

            if (queryParams.hasOwnProperty('end_time')) {
                iq.c("end_time").t(queryParams.begin_time).up();
            }

            if (queryParams.hasOwnProperty('meeting_code')) {
                iq.c("meeting_code").t(queryParams.meeting_code).up();
            }

            if (queryParams.hasOwnProperty('creator_uid')) {
                iq.c("creator_uid").t(queryParams.creator_uid).up();
            }

            if (queryParams.hasOwnProperty('is_creator')) {
                iq.c("is_creator").t(queryParams.is_creator).up();
            }

            if (queryParams.hasOwnProperty('is_invitee')) {
                iq.c("is_invitee").t(queryParams.is_invitee).up();
            }

            if (queryParams.hasOwnProperty('meeting_last_modify_time')) {
                iq.c("meeting_last_modify_time").t(queryParams.meeting_last_modify_time).up();
            }

            if (queryParams.hasOwnProperty('expect_meeting_count')) {
                iq.c("expect_meeting_count").t(queryParams.expect_meeting_count).up();
            }

            iq.c("meeting_state_list");
            if (_typeof(queryParams.meeting_state_list) === 'object' && Array.isArray(queryParams.meeting_state_list)) {
                var _iteratorNormalCompletion4 = true;
                var _didIteratorError4 = false;
                var _iteratorError4 = undefined;

                try {
                    for (var _iterator4 = queryParams.meeting_state_list[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
                        var state = _step4.value;

                        iq.c("meeting_state").t(state.toString()).up();
                    }
                } catch (err) {
                    _didIteratorError4 = true;
                    _iteratorError4 = err;
                } finally {
                    try {
                        if (!_iteratorNormalCompletion4 && _iterator4.return) {
                            _iterator4.return();
                        }
                    } finally {
                        if (_didIteratorError4) {
                            throw _iteratorError4;
                        }
                    }
                }
            } else {
                iq.c("meeting_state").t("0").up();
                iq.c("meeting_state").t("2").up().up();
            }

            this.sendIQ(iq, this.queryMeetingItemListResponseSuccess, this.queryMeetingItemListResponseError);
        }
    }, {
        key: "queryMeetingItemListResponseSuccess",
        value: function queryMeetingItemListResponseSuccess(msg) {
            var data = {
                more: null,
                meeting_item_list: []
            };
            var cb = this.getEventHandler('query_meeting_item_list');
            var mainNode = msg.getElementsByTagName('query_meeting_item_list')[0];
            if (mainNode.childNodes.length === 0) {
                cb(true, data);
                return;
            }

            var hasRemainNode = mainNode.getElementsByTagName("has_remain_meeting")[0];
            if (typeof hasRemainNode !== 'undefined') {
                data.more = get_val(mainNode, "has_remain_meeting") === "1";
            }

            var itemListNode = mainNode.getElementsByTagName('meeting_item_list')[0];
            if (typeof itemListNode !== 'undefined') {
                for (var i = 0; i < itemListNode.childNodes.length; i++) {
                    var itemNode = itemListNode.childNodes[i];
                    var single_meeting = this._parse_meeting_item(itemNode);
                    data.meeting_item_list.push(single_meeting);
                }
            }

            cb(true, data);
        }
    }, {
        key: "_parse_meeting_item",
        value: function _parse_meeting_item(itemNode) {
            var singleMeeting = {
                meeting_id: get_val(itemNode, 'meeting_id'),
                meeting_code: get_val(itemNode, 'meeting_code'),
                url: decodeB64ThenUtf8(get_val(itemNode, 'url')),
                pstn_phone: get_val(itemNode, 'pstn_phone'),
                pstn_code: get_val(itemNode, 'pstn_code'),
                begin_time: get_val(itemNode, 'begin_time'),
                end_time: get_val(itemNode, 'end_time'),
                last_modify_time: get_val(itemNode, 'last_modify_time'),
                password: get_val(itemNode, 'password'),
                need_auth: get_val(itemNode, 'need_auth', '1'),
                auth_type: get_val(itemNode, 'auth_type', '0'),
                is_quick_meeting: get_val(itemNode, 'create_type'),
                host: {
                    app_id: get_attr(itemNode, 'creator', 'app_id'),
                    app_uid: get_attr(itemNode, 'creator', "app_uid")
                },
                subject: decodeB64ThenUtf8(get_val(itemNode, 'subject')),
                location: decodeB64ThenUtf8(get_val(itemNode, 'location')),
                invite_list: []
            };

            if (itemNode.hasOwnProperty('invite_list')) {
                var invite_list_node = itemNode.getElementsByTagName('invite_list')[0];
                for (var i = 0; i < invite_list_node.childNodes.length; i++) {
                    var member_node = invite_list_node.childNodes[i];
                    data.invite_list.push({
                        app_id: member_node.getAttribute("app_id"),
                        app_uid: member_node.getAttribute("app_uid")
                    });
                }
            }

            return singleMeeting;
        }
    }, {
        key: "queryMeetingItemListResponseError",
        value: function queryMeetingItemListResponseError(msg) {
            this.genErrorCallback(msg, 'query_meeting_item_list')();
        }

        /**
         * 修改会议详情
         * @param confParams
         *      meeting_id | 会议ID
         *      subject | 会议主题
         *      begin_time | 	会议开始时间
         *      end_time | 会议ID结束时间
         *      password | 会议加入密码
         *      location | 会议场所
         *      host | 	主持人信息
         *      invite_list | 	被邀请成员名单
         */

    }, {
        key: "modifyMeetingItemRequest",
        value: function modifyMeetingItemRequest(confParams) {
            var iq = $iq({
                type: 'set'
            }).c("modify", { xmlns: "tencent:wemeet:meeting" }).c("meeting_id").t(confParams.meeting_id).up();

            if (confParams.hasOwnProperty("subject")) {
                iq.c("subject").t(encodeUtf8ThenB64(confParams.subject)).up();
            }
            if (confParams.hasOwnProperty("begin_time")) {
                iq.c("begin_time").t(confParams.begin_time).up();
            }
            if (confParams.hasOwnProperty("end_time")) {
                iq.c("end_time").t(confParams.end_time).up();
            }
            if (confParams.hasOwnProperty("password")) {
                iq.c("password").t(confParams.password).up();
            }
            if (confParams.hasOwnProperty("location")) {
                iq.c("location").t(encodeUtf8ThenB64(confParams.location)).up();
            }
            if (confParams.hasOwnProperty("host")) {
                iq.c("host", { app_uid: confParams.host.app_uid, app_id: confParams.host.app_id }).up();
            }
            if (confParams.hasOwnProperty("invite_list")) {
                iq.c("invite_list");
                for (var i = 0; i < confParams.invite_list.length; i++) {
                    var item = confParams.invite_list[i];
                    iq.c('member', { app_uid: item.app_uid, app_id: item.app_id }).up();
                }
            }

            this.sendIQ(iq, this.modifyMeetingItemResponseSuccess, this.modifyMeetingItemResponseError);
        }
    }, {
        key: "modifyMeetingItemResponseSuccess",
        value: function modifyMeetingItemResponseSuccess(msg) {
            var mainNode = msg.getElementsByTagName("modify")[0];
            var cb = this.getEventHandler('modify_meeting');
            cb(true, { msg: 'modify meeting info success' });
        }
    }, {
        key: "modifyMeetingItemResponseError",
        value: function modifyMeetingItemResponseError(msg) {
            this.genErrorCallback(msg, 'modify_meeting');
        }

        /**
         * 取消指定会议
         * @param cancelParams|要取消的会议信息结构
         *      meeting_id | 要取消的会议meeting_id
         *      reason | 取消会议的原因
         *      code | 取消会议的原因码|
         */

    }, {
        key: "cancelMeetingRequest",
        value: function cancelMeetingRequest(cancelParams) {
            var iq = $iq({
                type: 'set'
            }).c("cancel", { xmlns: "tencent:wemeet:meeting" }).c("meeting_id").t(cancelParams.meeting_id).up().c("reason", { code: cancelParams.code }).t(cancelParams.reason).up();
            this.sendIQ(iq, this.cancelMeetingResponseSuccess, this.cancelMeetingResponseError);
        }
    }, {
        key: "cancelMeetingResponseSuccess",
        value: function cancelMeetingResponseSuccess(msg) {
            var mainNode = msg.getElementsByTagName("cancel")[0];
            var cb = this.getEventHandler('cancel_meeting');
            cb(true, {});
        }
    }, {
        key: "cancelMeetingResponseError",
        value: function cancelMeetingResponseError(msg) {
            this.genErrorCallback(msg, 'cancel_meeting')();
        }

        /**
         * 加入会议
         * @param join_param
         *      meeting_code|app层传递的meeting code
         *      nickname|用户名
         *      password|密码
         *      video_on|加入房间后摄像头默认状态
         *      audio_on|加入房间后音频默认状态
         *      share_on|加入房间后屏幕分享默认状态
         */

    }, {
        key: "joinMeetingRequest",
        value: function joinMeetingRequest(join_param) {
            var iq = $iq({
                type: 'set'
            }).c("join", { xmlns: "tencent:wemeet:meeting" }).c("nickname").t(encodeUtf8ThenB64(join_param.nickname)).up().c("video_on").t(join_param.video_on).up().c("audio_on").t(join_param.audio_on).up().c("share_on").t(join_param.share_on).up();

            if (join_param.hasOwnProperty('password')) {
                iq.c("password").t(join_param.password).up();
            }

            if (join_param.hasOwnProperty("meeting_code")) {
                iq.c("meeting_code").t(join_param.meeting_code).up();
            }

            if (join_param.hasOwnProperty("meeting_id")) {
                iq.c("meeting_id").t(join_param.meeting_id).up();
            }

            this.sendIQ(iq, this.joinMeetingResponseSuccess, this.joinMeetingResponseError);
        }
    }, {
        key: "joinMeetingResponseSuccess",
        value: function joinMeetingResponseSuccess(msg) {
            var _this4 = this;

            console.log('xmpp joinMeetingResponseSuccess...');
            var itemNode = msg.getElementsByTagName("join")[0];
            var data = {
                meeting_id: itemNode.getElementsByTagName("meeting_id")[0].childNodes[0].nodeValue,
                av_room_id: itemNode.getElementsByTagName("av_room_id")[0].childNodes[0].nodeValue,
                av_user_id: itemNode.getElementsByTagName("av_user_id")[0].childNodes[0].nodeValue,
                media_platform_auth_token: get_val(itemNode, "media_platform_auth_token"),
                qcloud_user_signature: get_val(itemNode, "qcloud_user_signature"),
                qcloud_user_private_map_key: get_val(itemNode, "qcloud_user_private_map_key")
            };

            data.permission_list = [];
            var itemListNode = itemNode.getElementsByTagName('permission_list')[0];
            if (typeof itemListNode !== 'undefined') {
                for (var i = 0; i < itemListNode.childNodes.length; i++) {
                    var _itemNode = itemListNode.childNodes[i];
                    var permissionType = _itemNode.getAttribute('type');
                    var permissionIsGrant = _itemNode.getAttribute('is_grant');
                    data.permission_list.push({ "type": permissionType, "is_grant": permissionIsGrant });
                }
            }

            data.meeting_permission_list = [];
            itemListNode = itemNode.getElementsByTagName('meeting_permission_list')[0];
            if (typeof itemListNode !== 'undefined') {
                for (var _i = 0; _i < itemListNode.childNodes.length; _i++) {
                    var _itemNode2 = itemListNode.childNodes[_i];
                    // let permissionType = get_attr(itemNode, 'permission', 'type');
                    // let permissionState = get_attr(itemNode, 'permission', 'state');
                    var _permissionType = _itemNode2.getAttribute('type');
                    var permissionState = _itemNode2.getAttribute('state');
                    data.meeting_permission_list.push({ "type": _permissionType, "state": permissionState });
                }
            }

            var cb = this.getEventHandler('join_meeting');
            cb(true, data);

            this.meetingPingTimer = setInterval(function () {
                _this4.meetingPingRequest(data.meeting_id);
            }, 5000);
        }
    }, {
        key: "joinMeetingResponseError",
        value: function joinMeetingResponseError(msg) {
            this.genErrorCallback(msg, 'join_meeting')();
        }

        /**
         * 退出会议
         * @param meeting_id
         */

    }, {
        key: "leaveMeetingRequest",
        value: function leaveMeetingRequest(meeting_id) {
            var iq = $iq({
                type: 'set'
            }).c("user_status", { xmlns: "tencent:wemeet:meeting_ctrl" }).c("meeting_id").t(meeting_id).up().c("type").t(2).up();
            this.sendIQ(iq, this.leaveMeetingResponseSuccess, this.leaveMeetingResponseError);
        }
    }, {
        key: "leaveMeetingResponseSuccess",
        value: function leaveMeetingResponseSuccess(msg) {
            if (this.meetingPingTimer) {
                clearInterval(this.meetingPingTimer);
                this.meetingPingTimer = null;
            }
            var cb = this.getEventHandler('leave_meeting');
            cb(true, { msg: 'left from meeting' });
        }
    }, {
        key: "leaveMeetingResponseError",
        value: function leaveMeetingResponseError(msg) {
            this.genErrorCallback(msg, 'leave_meeting')();
        }
    }, {
        key: "finishKickedOutRequest",
        value: function finishKickedOutRequest(meetingId) {
            var _this5 = this;

            var iq = $iq({
                type: 'set'
            }).c("user_status", { xmlns: "tencent:wemeet:meeting_ctrl" }).c("meeting_id").t(meetingId).up().c("type").t(4).up();
            this.sendIQ(iq, function (succData) {
                _this5.logger.debug(succData);
            }, function (errorData) {
                _this5.logger.debug(errorData);
            });
        }

        /**
         * 解散会议
         * @param meetingParams
         */

    }, {
        key: "dissolveMeetingRequest",
        value: function dissolveMeetingRequest(meetingParams) {
            var iq = $iq({
                type: 'set'
            }).c("dissolve", { xmlns: "tencent:wemeet:meeting" }).c("meeting_id").t(meetingParams.meeting_id).up().c("reason", { code: meetingParams.code }).t(meetingParams.reason).up();
            this.sendIQ(iq, this.dissolveMeetingResponseSuccess, this.dissolveMeetingResponseError);
        }
    }, {
        key: "dissolveMeetingResponseSuccess",
        value: function dissolveMeetingResponseSuccess(msg) {
            var mainNode = msg.getElementsByTagName("dissolve")[0];
            var cb = this.getEventHandler('dissolve_meeting');
            cb(true, {
                msg: 'dissolve meeting success',
                data: mainNode
            });
        }
    }, {
        key: "dissolveMeetingResponseError",
        value: function dissolveMeetingResponseError(msg) {
            this.genErrorCallback(msg, 'dissolve_meeting')();
        }
    }, {
        key: "modifyNicknameRequest",
        value: function modifyNicknameRequest(meetingId, account, nickname) {
            var _this6 = this;

            var iq = $iq({
                type: 'set'
            }).c("modify_user_info", { xmlns: "tencent:wemeet:meeting_ctrl" }).c("meeting_id").t(meetingId).up().c("user_list").c("item").c("id", { app_uid: account.uid, app_id: account.app_id, instance_id: account.instance_id }).up().c("nickname").t(encodeUtf8ThenB64(nickname));
            this.sendIQ(iq, function (succData) {
                var cb = _this6.getEventHandler('modify_user_info');
                cb(true, { msg: 'modify_user_info success', data: succData });
            }, function (errorData) {
                _this6.genErrorCallback(errorData, 'modify_user_info')();
            });
        }

        // todo

    }, {
        key: "setVideoLayoutRequest",
        value: function setVideoLayoutRequest() {
            // set_video_layout
        }
    }, {
        key: "kickoutRequest",
        value: function kickoutRequest(meetingId, accountList, reason) {
            var _this7 = this;

            var iq = $iq({
                type: 'set'
            }).c("kick_out", { xmlns: "tencent:wemeet:meeting_ctrl" }).c("meeting_id").t(meetingId).up().c("reason", { code: 0 }).t(reason).up().c("user_list");
            var _iteratorNormalCompletion5 = true;
            var _didIteratorError5 = false;
            var _iteratorError5 = undefined;

            try {
                for (var _iterator5 = accountList[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
                    var account = _step5.value;

                    iq.c("id", { app_uid: account.uid, app_id: account.app_id, instance_id: account.instance_id }).up();
                }
            } catch (err) {
                _didIteratorError5 = true;
                _iteratorError5 = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion5 && _iterator5.return) {
                        _iterator5.return();
                    }
                } finally {
                    if (_didIteratorError5) {
                        throw _iteratorError5;
                    }
                }
            }

            this.sendIQ(iq, function (succData) {
                var cb = _this7.getEventHandler('kickout');
                cb(true, { msg: 'modify_user_info success', data: succData });
            }, function (errorData) {
                _this7.genErrorCallback(errorData, 'kickout')();
            });
        }
    }, {
        key: "meetingPingRequest",
        value: function meetingPingRequest(meeting_id) {
            var _this8 = this;

            var iq = $iq({
                type: 'get'
            }).c("ping", { xmlns: "tencent:wemeet:ping" }).c("meeting_id").t(meeting_id);
            this.sendIQ(iq, function (succMsg) {
                return succMsg;
            }, function (msg) {
                console.log(msg);
                if (typeof msg !== 'undefined' && msg) {
                    if (_this8.meetingPingTimer) {
                        clearInterval(_this8.meetingPingTimer);
                        _this8.meetingPingTimer = null;
                    }
                    var itemNode = msg.getElementsByTagName("ping")[0];
                    var errorMsg = get_val(itemNode, "error");
                    var errorCode = get_attr(itemNode, "error", "code");
                    console.log("meeting ping error, code:", errorCode, ", msg:", errorMsg);
                    var cb = _this8.getEventHandler('leave_meeting');
                    cb(true, { msg: 'leave from meeting bacause ping recv bad rep.' });
                }
            });
        }
    }], [{
        key: "getInstance",
        value: function getInstance() {
            if (XmppService.prototype.instance === undefined) {
                XmppService.prototype.instance = new XmppService();
            }
            return XmppService.prototype.instance;
        }
    }]);

    return XmppService;
}();

module.exports = XmppService;

/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

/**
 * @license almond 0.3.3 Copyright jQuery Foundation and other contributors.
 * Released under MIT license, http://github.com/requirejs/almond/LICENSE
 */

/*
    This program is distributed under the terms of the MIT license.
    Please see the LICENSE file for details.

    Copyright 2006-2008, OGG, LLC
*/

/*
 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
 * in FIPS PUB 180-1
 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for details.
 */

/*
 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
 * Digest Algorithm, as defined in RFC 1321.
 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
 * Distributed under the BSD License
 * See http://pajhome.org.uk/crypt/md5 for more info.
 */

!function (t, e) {
  if (true) !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (e),
				__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
				(__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
				__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));else { var n; }
}(undefined, function () {
  var t, e, n;return function (i) {
    function s(t, e) {
      return y.call(t, e);
    }function r(t, e) {
      var n,
          i,
          s,
          r,
          o,
          a,
          h,
          c,
          u,
          l,
          d,
          _,
          f = e && e.split("/"),
          p = b.map,
          m = p && p["*"] || {};if (t) {
        for (t = t.split("/"), o = t.length - 1, b.nodeIdCompat && x.test(t[o]) && (t[o] = t[o].replace(x, "")), "." === t[0].charAt(0) && f && (_ = f.slice(0, f.length - 1), t = _.concat(t)), u = 0; u < t.length; u++) {
          if ("." === (d = t[u])) t.splice(u, 1), u -= 1;else if (".." === d) {
            if (0 === u || 1 === u && ".." === t[2] || ".." === t[u - 1]) continue;u > 0 && (t.splice(u - 1, 2), u -= 2);
          }
        }t = t.join("/");
      }if ((f || m) && p) {
        for (n = t.split("/"), u = n.length; u > 0; u -= 1) {
          if (i = n.slice(0, u).join("/"), f) for (l = f.length; l > 0; l -= 1) {
            if ((s = p[f.slice(0, l).join("/")]) && (s = s[i])) {
              r = s, a = u;break;
            }
          }if (r) break;!h && m && m[i] && (h = m[i], c = u);
        }!r && h && (r = h, a = c), r && (n.splice(0, a, r), t = n.join("/"));
      }return t;
    }function o(t, e) {
      return function () {
        var n = T.call(arguments, 0);return "string" != typeof n[0] && 1 === n.length && n.push(null), _f.apply(i, n.concat([t, e]));
      };
    }function a(t) {
      return function (e) {
        return r(e, t);
      };
    }function h(t) {
      return function (e) {
        g[t] = e;
      };
    }function c(t) {
      if (s(S, t)) {
        var e = S[t];delete S[t], v[t] = !0, _.apply(i, e);
      }if (!s(g, t) && !s(v, t)) throw new Error("No " + t);return g[t];
    }function u(t) {
      var e,
          n = t ? t.indexOf("!") : -1;return n > -1 && (e = t.substring(0, n), t = t.substring(n + 1, t.length)), [e, t];
    }function l(t) {
      return t ? u(t) : [];
    }function d(t) {
      return function () {
        return b && b.config && b.config[t] || {};
      };
    }var _,
        _f,
        p,
        m,
        g = {},
        S = {},
        b = {},
        v = {},
        y = Object.prototype.hasOwnProperty,
        T = [].slice,
        x = /\.js$/;p = function p(t, e) {
      var n,
          i = u(t),
          s = i[0],
          o = e[1];return t = i[1], s && (s = r(s, o), n = c(s)), s ? t = n && n.normalize ? n.normalize(t, a(o)) : r(t, o) : (t = r(t, o), i = u(t), s = i[0], t = i[1], s && (n = c(s))), { f: s ? s + "!" + t : t, n: t, pr: s, p: n };
    }, m = { require: function require(t) {
        return o(t);
      }, exports: function exports(t) {
        var e = g[t];return void 0 !== e ? e : g[t] = {};
      }, module: function module(t) {
        return { id: t, uri: "", exports: g[t], config: d(t) };
      } }, _ = function _(t, e, n, r) {
      var a,
          u,
          d,
          _,
          f,
          b,
          y,
          T = [],
          x = typeof n === "undefined" ? "undefined" : _typeof(n);if (r = r || t, b = l(r), "undefined" === x || "function" === x) {
        for (e = !e.length && n.length ? ["require", "exports", "module"] : e, f = 0; f < e.length; f += 1) {
          if (_ = p(e[f], b), "require" === (u = _.f)) T[f] = m.require(t);else if ("exports" === u) T[f] = m.exports(t), y = !0;else if ("module" === u) a = T[f] = m.module(t);else if (s(g, u) || s(S, u) || s(v, u)) T[f] = c(u);else {
            if (!_.p) throw new Error(t + " missing " + u);_.p.load(_.n, o(r, !0), h(u), {}), T[f] = g[u];
          }
        }d = n ? n.apply(g[t], T) : void 0, t && (a && a.exports !== i && a.exports !== g[t] ? g[t] = a.exports : d === i && y || (g[t] = d));
      } else t && (g[t] = n);
    }, t = e = _f = function f(t, e, n, s, r) {
      if ("string" == typeof t) return m[t] ? m[t](e) : c(p(t, l(e)).f);if (!t.splice) {
        if (b = t, b.deps && _f(b.deps, b.callback), !e) return;e.splice ? (t = e, e = n, n = null) : t = i;
      }return e = e || function () {}, "function" == typeof n && (n = s, s = r), s ? _(i, t, e, n) : setTimeout(function () {
        _(i, t, e, n);
      }, 4), _f;
    }, _f.config = function (t) {
      return _f(t);
    }, t._defined = g, n = function n(t, e, _n) {
      if ("string" != typeof t) throw new Error("See almond README: incorrect module build, no module name");e.splice || (_n = e, e = []), s(g, t) || s(S, t) || (S[t] = [t, e, _n]);
    }, n.amd = { jQuery: !0 };
  }(), n("node_modules/almond/almond.js", function () {}), function (t, e) {
    if ("function" != typeof n || !n.amd) return e(t);n("strophe-polyfill", [], function () {
      return e(t);
    });
  }(this, function (t) {
    Function.prototype.bind || (Function.prototype.bind = function (t) {
      var e = this,
          n = Array.prototype.slice,
          i = Array.prototype.concat,
          s = n.call(arguments, 1);return function () {
        return e.apply(t || this, i.call(s, n.call(arguments, 0)));
      };
    }), Array.isArray || (Array.isArray = function (t) {
      return "[object Array]" === Object.prototype.toString.call(t);
    }), Array.prototype.indexOf || (Array.prototype.indexOf = function (t) {
      var e = this.length,
          n = Number(arguments[1]) || 0;for (n = n < 0 ? Math.ceil(n) : Math.floor(n), n < 0 && (n += e); n < e; n++) {
        if (n in this && this[n] === t) return n;
      }return -1;
    }), Array.prototype.forEach || (Array.prototype.forEach = function (t, e) {
      var n, i;if (null === this) throw new TypeError(" this is null or not defined");var s = Object(this),
          r = s.length >>> 0;if ("function" != typeof t) throw new TypeError(t + " is not a function");for (arguments.length > 1 && (n = e), i = 0; i < r;) {
        var o;i in s && (o = s[i], t.call(n, o, i, s)), i++;
      }
    });var e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.btoa || (t.btoa = function (t) {
      var n,
          i,
          s,
          r,
          o,
          a,
          h,
          c = "",
          u = 0;do {
        n = t.charCodeAt(u++), i = t.charCodeAt(u++), s = t.charCodeAt(u++), r = n >> 2, o = (3 & n) << 4 | i >> 4, a = (15 & i) << 2 | s >> 6, h = 63 & s, isNaN(i) ? (o = (3 & n) << 4, a = h = 64) : isNaN(s) && (h = 64), c = c + e.charAt(r) + e.charAt(o) + e.charAt(a) + e.charAt(h);
      } while (u < t.length);return c;
    }), t.atob || (t.atob = function (t) {
      var n,
          i,
          s,
          r,
          o,
          a,
          h,
          c = "",
          u = 0;t = t.replace(/[^A-Za-z0-9\+\/\=]/g, "");do {
        r = e.indexOf(t.charAt(u++)), o = e.indexOf(t.charAt(u++)), a = e.indexOf(t.charAt(u++)), h = e.indexOf(t.charAt(u++)), n = r << 2 | o >> 4, i = (15 & o) << 4 | a >> 2, s = (3 & a) << 6 | h, c += String.fromCharCode(n), 64 !== a && (c += String.fromCharCode(i)), 64 !== h && (c += String.fromCharCode(s));
      } while (u < t.length);return c;
    });
  }), function (t, e) {
    "function" == typeof n && n.amd ? n("strophe-sha1", [], function () {
      return e();
    }) : t.SHA1 = e();
  }(this, function () {
    function t(t, i) {
      t[i >> 5] |= 128 << 24 - i % 32, t[15 + (i + 64 >> 9 << 4)] = i;var o,
          a,
          h,
          c,
          u,
          l,
          d,
          _,
          f = new Array(80),
          p = 1732584193,
          m = -271733879,
          g = -1732584194,
          S = 271733878,
          b = -1009589776;for (o = 0; o < t.length; o += 16) {
        for (c = p, u = m, l = g, d = S, _ = b, a = 0; a < 80; a++) {
          f[a] = a < 16 ? t[o + a] : r(f[a - 3] ^ f[a - 8] ^ f[a - 14] ^ f[a - 16], 1), h = s(s(r(p, 5), e(a, m, g, S)), s(s(b, f[a]), n(a))), b = S, S = g, g = r(m, 30), m = p, p = h;
        }p = s(p, c), m = s(m, u), g = s(g, l), S = s(S, d), b = s(b, _);
      }return [p, m, g, S, b];
    }function e(t, e, n, i) {
      return t < 20 ? e & n | ~e & i : t < 40 ? e ^ n ^ i : t < 60 ? e & n | e & i | n & i : e ^ n ^ i;
    }function n(t) {
      return t < 20 ? 1518500249 : t < 40 ? 1859775393 : t < 60 ? -1894007588 : -899497514;
    }function i(e, n) {
      var i = o(e);i.length > 16 && (i = t(i, 8 * e.length));for (var s = new Array(16), r = new Array(16), a = 0; a < 16; a++) {
        s[a] = 909522486 ^ i[a], r[a] = 1549556828 ^ i[a];
      }var h = t(s.concat(o(n)), 512 + 8 * n.length);return t(r.concat(h), 672);
    }function s(t, e) {
      var n = (65535 & t) + (65535 & e);return (t >> 16) + (e >> 16) + (n >> 16) << 16 | 65535 & n;
    }function r(t, e) {
      return t << e | t >>> 32 - e;
    }function o(t) {
      for (var e = [], n = 0; n < 8 * t.length; n += 8) {
        e[n >> 5] |= (255 & t.charCodeAt(n / 8)) << 24 - n % 32;
      }return e;
    }function a(t) {
      for (var e = "", n = 0; n < 32 * t.length; n += 8) {
        e += String.fromCharCode(t[n >> 5] >>> 24 - n % 32 & 255);
      }return e;
    }function h(t) {
      for (var e, n, i = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", s = "", r = 0; r < 4 * t.length; r += 3) {
        for (e = (t[r >> 2] >> 8 * (3 - r % 4) & 255) << 16 | (t[r + 1 >> 2] >> 8 * (3 - (r + 1) % 4) & 255) << 8 | t[r + 2 >> 2] >> 8 * (3 - (r + 2) % 4) & 255, n = 0; n < 4; n++) {
          8 * r + 6 * n > 32 * t.length ? s += "=" : s += i.charAt(e >> 6 * (3 - n) & 63);
        }
      }return s;
    }return { b64_hmac_sha1: function b64_hmac_sha1(t, e) {
        return h(i(t, e));
      }, b64_sha1: function b64_sha1(e) {
        return h(t(o(e), 8 * e.length));
      }, binb2str: a, core_hmac_sha1: i, str_hmac_sha1: function str_hmac_sha1(t, e) {
        return a(i(t, e));
      }, str_sha1: function str_sha1(e) {
        return a(t(o(e), 8 * e.length));
      } };
  }), function (t, e) {
    "function" == typeof n && n.amd ? n("strophe-md5", [], function () {
      return e();
    }) : t.MD5 = e();
  }(this, function () {
    var t = function t(_t, e) {
      var n = (65535 & _t) + (65535 & e);return (_t >> 16) + (e >> 16) + (n >> 16) << 16 | 65535 & n;
    },
        e = function e(t, _e) {
      return t << _e | t >>> 32 - _e;
    },
        n = function n(t) {
      for (var e = [], n = 0; n < 8 * t.length; n += 8) {
        e[n >> 5] |= (255 & t.charCodeAt(n / 8)) << n % 32;
      }return e;
    },
        i = function i(t) {
      for (var e = "", n = 0; n < 32 * t.length; n += 8) {
        e += String.fromCharCode(t[n >> 5] >>> n % 32 & 255);
      }return e;
    },
        s = function s(t) {
      for (var e = "0123456789abcdef", n = "", i = 0; i < 4 * t.length; i++) {
        n += e.charAt(t[i >> 2] >> i % 4 * 8 + 4 & 15) + e.charAt(t[i >> 2] >> i % 4 * 8 & 15);
      }return n;
    },
        r = function r(n, i, s, _r, o, a) {
      return t(e(t(t(i, n), t(_r, a)), o), s);
    },
        o = function o(t, e, n, i, s, _o, a) {
      return r(e & n | ~e & i, t, e, s, _o, a);
    },
        a = function a(t, e, n, i, s, o, _a) {
      return r(e & i | n & ~i, t, e, s, o, _a);
    },
        h = function h(t, e, n, i, s, o, a) {
      return r(e ^ n ^ i, t, e, s, o, a);
    },
        c = function c(t, e, n, i, s, o, a) {
      return r(n ^ (e | ~i), t, e, s, o, a);
    },
        u = function u(e, n) {
      e[n >> 5] |= 128 << n % 32, e[14 + (n + 64 >>> 9 << 4)] = n;for (var i, s, r, u, l = 1732584193, d = -271733879, _ = -1732584194, f = 271733878, p = 0; p < e.length; p += 16) {
        i = l, s = d, r = _, u = f, l = o(l, d, _, f, e[p + 0], 7, -680876936), f = o(f, l, d, _, e[p + 1], 12, -389564586), _ = o(_, f, l, d, e[p + 2], 17, 606105819), d = o(d, _, f, l, e[p + 3], 22, -1044525330), l = o(l, d, _, f, e[p + 4], 7, -176418897), f = o(f, l, d, _, e[p + 5], 12, 1200080426), _ = o(_, f, l, d, e[p + 6], 17, -1473231341), d = o(d, _, f, l, e[p + 7], 22, -45705983), l = o(l, d, _, f, e[p + 8], 7, 1770035416), f = o(f, l, d, _, e[p + 9], 12, -1958414417), _ = o(_, f, l, d, e[p + 10], 17, -42063), d = o(d, _, f, l, e[p + 11], 22, -1990404162), l = o(l, d, _, f, e[p + 12], 7, 1804603682), f = o(f, l, d, _, e[p + 13], 12, -40341101), _ = o(_, f, l, d, e[p + 14], 17, -1502002290), d = o(d, _, f, l, e[p + 15], 22, 1236535329), l = a(l, d, _, f, e[p + 1], 5, -165796510), f = a(f, l, d, _, e[p + 6], 9, -1069501632), _ = a(_, f, l, d, e[p + 11], 14, 643717713), d = a(d, _, f, l, e[p + 0], 20, -373897302), l = a(l, d, _, f, e[p + 5], 5, -701558691), f = a(f, l, d, _, e[p + 10], 9, 38016083), _ = a(_, f, l, d, e[p + 15], 14, -660478335), d = a(d, _, f, l, e[p + 4], 20, -405537848), l = a(l, d, _, f, e[p + 9], 5, 568446438), f = a(f, l, d, _, e[p + 14], 9, -1019803690), _ = a(_, f, l, d, e[p + 3], 14, -187363961), d = a(d, _, f, l, e[p + 8], 20, 1163531501), l = a(l, d, _, f, e[p + 13], 5, -1444681467), f = a(f, l, d, _, e[p + 2], 9, -51403784), _ = a(_, f, l, d, e[p + 7], 14, 1735328473), d = a(d, _, f, l, e[p + 12], 20, -1926607734), l = h(l, d, _, f, e[p + 5], 4, -378558), f = h(f, l, d, _, e[p + 8], 11, -2022574463), _ = h(_, f, l, d, e[p + 11], 16, 1839030562), d = h(d, _, f, l, e[p + 14], 23, -35309556), l = h(l, d, _, f, e[p + 1], 4, -1530992060), f = h(f, l, d, _, e[p + 4], 11, 1272893353), _ = h(_, f, l, d, e[p + 7], 16, -155497632), d = h(d, _, f, l, e[p + 10], 23, -1094730640), l = h(l, d, _, f, e[p + 13], 4, 681279174), f = h(f, l, d, _, e[p + 0], 11, -358537222), _ = h(_, f, l, d, e[p + 3], 16, -722521979), d = h(d, _, f, l, e[p + 6], 23, 76029189), l = h(l, d, _, f, e[p + 9], 4, -640364487), f = h(f, l, d, _, e[p + 12], 11, -421815835), _ = h(_, f, l, d, e[p + 15], 16, 530742520), d = h(d, _, f, l, e[p + 2], 23, -995338651), l = c(l, d, _, f, e[p + 0], 6, -198630844), f = c(f, l, d, _, e[p + 7], 10, 1126891415), _ = c(_, f, l, d, e[p + 14], 15, -1416354905), d = c(d, _, f, l, e[p + 5], 21, -57434055), l = c(l, d, _, f, e[p + 12], 6, 1700485571), f = c(f, l, d, _, e[p + 3], 10, -1894986606), _ = c(_, f, l, d, e[p + 10], 15, -1051523), d = c(d, _, f, l, e[p + 1], 21, -2054922799), l = c(l, d, _, f, e[p + 8], 6, 1873313359), f = c(f, l, d, _, e[p + 15], 10, -30611744), _ = c(_, f, l, d, e[p + 6], 15, -1560198380), d = c(d, _, f, l, e[p + 13], 21, 1309151649), l = c(l, d, _, f, e[p + 4], 6, -145523070), f = c(f, l, d, _, e[p + 11], 10, -1120210379), _ = c(_, f, l, d, e[p + 2], 15, 718787259), d = c(d, _, f, l, e[p + 9], 21, -343485551), l = t(l, i), d = t(d, s), _ = t(_, r), f = t(f, u);
      }return [l, d, _, f];
    };return { hexdigest: function hexdigest(t) {
        return s(u(n(t), 8 * t.length));
      }, hash: function hash(t) {
        return i(u(n(t), 8 * t.length));
      } };
  }), function (t, e) {
    "function" == typeof n && n.amd ? n("strophe-utils", [], function () {
      return e();
    }) : t.stropheUtils = e();
  }(this, function () {
    return { utf16to8: function utf16to8(t) {
        var e,
            n,
            i = "",
            s = t.length;for (e = 0; e < s; e++) {
          n = t.charCodeAt(e), n >= 0 && n <= 127 ? i += t.charAt(e) : n > 2047 ? (i += String.fromCharCode(224 | n >> 12 & 15), i += String.fromCharCode(128 | n >> 6 & 63), i += String.fromCharCode(128 | n >> 0 & 63)) : (i += String.fromCharCode(192 | n >> 6 & 31), i += String.fromCharCode(128 | n >> 0 & 63));
        }return i;
      }, addCookies: function addCookies(t) {
        var e, n, i, s, r, o, a;for (e in t || {}) {
          r = "", o = "", a = "", n = t[e], i = "object" == (typeof n === "undefined" ? "undefined" : _typeof(n)), s = escape(unescape(i ? n.value : n)), i && (r = n.expires ? ";expires=" + n.expires : "", o = n.domain ? ";domain=" + n.domain : "", a = n.path ? ";path=" + n.path : ""), document.cookie = e + "=" + s + r + o + a;
        }
      } };
  }), function (t, e) {
    if ("function" == typeof n && n.amd) n("strophe-core", ["strophe-sha1", "strophe-md5", "strophe-utils"], function () {
      return e.apply(this, arguments);
    });else {
      var i = e(t.SHA1, t.MD5, t.stropheUtils);t.Strophe = i.Strophe, t.$build = i.$build, t.$iq = i.$iq, t.$msg = i.$msg, t.$pres = i.$pres, t.SHA1 = i.SHA1, t.MD5 = i.MD5, t.b64_hmac_sha1 = i.SHA1.b64_hmac_sha1, t.b64_sha1 = i.SHA1.b64_sha1, t.str_hmac_sha1 = i.SHA1.str_hmac_sha1, t.str_sha1 = i.SHA1.str_sha1;
    }
  }(this, function (t, e, n) {
    function i(t, e) {
      return new a.Builder(t, e);
    }function s(t) {
      return new a.Builder("message", t);
    }function r(t) {
      return new a.Builder("iq", t);
    }function o(t) {
      return new a.Builder("presence", t);
    }var a;return a = { VERSION: "", NS: { HTTPBIND: "http://jabber.org/protocol/httpbind", BOSH: "urn:xmpp:xbosh", CLIENT: "jabber:client", AUTH: "jabber:iq:auth", ROSTER: "jabber:iq:roster", PROFILE: "jabber:iq:profile", DISCO_INFO: "http://jabber.org/protocol/disco#info", DISCO_ITEMS: "http://jabber.org/protocol/disco#items", MUC: "http://jabber.org/protocol/muc", SASL: "urn:ietf:params:xml:ns:xmpp-sasl", STREAM: "http://etherx.jabber.org/streams", FRAMING: "urn:ietf:params:xml:ns:xmpp-framing", BIND: "urn:ietf:params:xml:ns:xmpp-bind", SESSION: "urn:ietf:params:xml:ns:xmpp-session", VERSION: "jabber:iq:version", STANZAS: "urn:ietf:params:xml:ns:xmpp-stanzas", XHTML_IM: "http://jabber.org/protocol/xhtml-im", XHTML: "http://www.w3.org/1999/xhtml" }, XHTML: { tags: ["a", "blockquote", "br", "cite", "em", "img", "li", "ol", "p", "span", "strong", "ul", "body"], attributes: { a: ["href"], blockquote: ["style"], br: [], cite: ["style"], em: [], img: ["src", "alt", "style", "height", "width"], li: ["style"], ol: ["style"], p: ["style"], span: ["style"], strong: [], ul: ["style"], body: [] }, css: ["background-color", "color", "font-family", "font-size", "font-style", "font-weight", "margin-left", "margin-right", "text-align", "text-decoration"], validTag: function validTag(t) {
          for (var e = 0; e < a.XHTML.tags.length; e++) {
            if (t === a.XHTML.tags[e]) return !0;
          }return !1;
        }, validAttribute: function validAttribute(t, e) {
          if (void 0 !== a.XHTML.attributes[t] && a.XHTML.attributes[t].length > 0) for (var n = 0; n < a.XHTML.attributes[t].length; n++) {
            if (e === a.XHTML.attributes[t][n]) return !0;
          }return !1;
        }, validCSS: function validCSS(t) {
          for (var e = 0; e < a.XHTML.css.length; e++) {
            if (t === a.XHTML.css[e]) return !0;
          }return !1;
        } }, Status: { ERROR: 0, CONNECTING: 1, CONNFAIL: 2, AUTHENTICATING: 3, AUTHFAIL: 4, CONNECTED: 5, DISCONNECTED: 6, DISCONNECTING: 7, ATTACHED: 8, REDIRECT: 9, CONNTIMEOUT: 10 }, LogLevel: { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, FATAL: 4 }, ElementType: { NORMAL: 1, TEXT: 3, CDATA: 4, FRAGMENT: 11 }, TIMEOUT: 1.1, SECONDARY_TIMEOUT: .1, addNamespace: function addNamespace(t, e) {
        a.NS[t] = e;
      }, forEachChild: function forEachChild(t, e, n) {
        var i, s;for (i = 0; i < t.childNodes.length; i++) {
          s = t.childNodes[i], s.nodeType !== a.ElementType.NORMAL || e && !this.isTagEqual(s, e) || n(s);
        }
      }, isTagEqual: function isTagEqual(t, e) {
        return t.tagName === e;
      }, _xmlGenerator: null, _makeGenerator: function _makeGenerator() {
        var t;return void 0 === document.implementation.createDocument || document.implementation.createDocument && document.documentMode && document.documentMode < 10 ? (t = this._getIEXmlDom(), t.appendChild(t.createElement("strophe"))) : t = document.implementation.createDocument("jabber:client", "strophe", null), t;
      }, xmlGenerator: function xmlGenerator() {
        return a._xmlGenerator || (a._xmlGenerator = a._makeGenerator()), a._xmlGenerator;
      }, _getIEXmlDom: function _getIEXmlDom() {
        for (var t = null, e = ["Msxml2.DOMDocument.6.0", "Msxml2.DOMDocument.5.0", "Msxml2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XMLDOM"], n = 0; n < e.length && null === t; n++) {
          try {
            t = new ActiveXObject(e[n]);
          } catch (e) {
            t = null;
          }
        }return t;
      }, xmlElement: function xmlElement(t) {
        if (!t) return null;var e,
            n,
            i,
            s = a.xmlGenerator().createElement(t);for (e = 1; e < arguments.length; e++) {
          var r = arguments[e];if (r) if ("string" == typeof r || "number" == typeof r) s.appendChild(a.xmlTextNode(r));else if ("object" == (typeof r === "undefined" ? "undefined" : _typeof(r)) && "function" == typeof r.sort) for (n = 0; n < r.length; n++) {
            var o = r[n];"object" == (typeof o === "undefined" ? "undefined" : _typeof(o)) && "function" == typeof o.sort && void 0 !== o[1] && null !== o[1] && s.setAttribute(o[0], o[1]);
          } else if ("object" == (typeof r === "undefined" ? "undefined" : _typeof(r))) for (i in r) {
            r.hasOwnProperty(i) && void 0 !== r[i] && null !== r[i] && s.setAttribute(i, r[i]);
          }
        }return s;
      }, xmlescape: function xmlescape(t) {
        return t = t.replace(/\&/g, "&amp;"), t = t.replace(/</g, "&lt;"), t = t.replace(/>/g, "&gt;"), t = t.replace(/'/g, "&apos;"), t = t.replace(/"/g, "&quot;");
      }, xmlunescape: function xmlunescape(t) {
        return t = t.replace(/\&amp;/g, "&"), t = t.replace(/&lt;/g, "<"), t = t.replace(/&gt;/g, ">"), t = t.replace(/&apos;/g, "'"), t = t.replace(/&quot;/g, '"');
      }, xmlTextNode: function xmlTextNode(t) {
        return a.xmlGenerator().createTextNode(t);
      }, xmlHtmlNode: function xmlHtmlNode(t) {
        var e;if (DOMParser) {
          e = new DOMParser().parseFromString(t, "text/xml");
        } else e = new ActiveXObject("Microsoft.XMLDOM"), e.async = "false", e.loadXML(t);return e;
      }, getText: function getText(t) {
        if (!t) return null;var e = "";0 === t.childNodes.length && t.nodeType === a.ElementType.TEXT && (e += t.nodeValue);for (var n = 0; n < t.childNodes.length; n++) {
          t.childNodes[n].nodeType === a.ElementType.TEXT && (e += t.childNodes[n].nodeValue);
        }return a.xmlescape(e);
      }, copyElement: function copyElement(t) {
        var e, n;if (t.nodeType === a.ElementType.NORMAL) {
          for (n = a.xmlElement(t.tagName), e = 0; e < t.attributes.length; e++) {
            n.setAttribute(t.attributes[e].nodeName, t.attributes[e].value);
          }for (e = 0; e < t.childNodes.length; e++) {
            n.appendChild(a.copyElement(t.childNodes[e]));
          }
        } else t.nodeType === a.ElementType.TEXT && (n = a.xmlGenerator().createTextNode(t.nodeValue));return n;
      }, createHtml: function createHtml(t) {
        var e, n, i, s, r, o, h, c, u, l, d;if (t.nodeType === a.ElementType.NORMAL) {
          if (s = t.nodeName.toLowerCase(), a.XHTML.validTag(s)) try {
            for (n = a.xmlElement(s), e = 0; e < a.XHTML.attributes[s].length; e++) {
              if (r = a.XHTML.attributes[s][e], void 0 !== (o = t.getAttribute(r)) && null !== o && "" !== o && !1 !== o && 0 !== o) if ("style" === r && "object" == (typeof o === "undefined" ? "undefined" : _typeof(o)) && void 0 !== o.cssText && (o = o.cssText), "style" === r) {
                for (h = [], c = o.split(";"), i = 0; i < c.length; i++) {
                  u = c[i].split(":"), l = u[0].replace(/^\s*/, "").replace(/\s*$/, "").toLowerCase(), a.XHTML.validCSS(l) && (d = u[1].replace(/^\s*/, "").replace(/\s*$/, ""), h.push(l + ": " + d));
                }h.length > 0 && (o = h.join("; "), n.setAttribute(r, o));
              } else n.setAttribute(r, o);
            }for (e = 0; e < t.childNodes.length; e++) {
              n.appendChild(a.createHtml(t.childNodes[e]));
            }
          } catch (t) {
            n = a.xmlTextNode("");
          } else for (n = a.xmlGenerator().createDocumentFragment(), e = 0; e < t.childNodes.length; e++) {
            n.appendChild(a.createHtml(t.childNodes[e]));
          }
        } else if (t.nodeType === a.ElementType.FRAGMENT) for (n = a.xmlGenerator().createDocumentFragment(), e = 0; e < t.childNodes.length; e++) {
          n.appendChild(a.createHtml(t.childNodes[e]));
        } else t.nodeType === a.ElementType.TEXT && (n = a.xmlTextNode(t.nodeValue));return n;
      }, escapeNode: function escapeNode(t) {
        return "string" != typeof t ? t : t.replace(/^\s+|\s+$/g, "").replace(/\\/g, "\\5c").replace(/ /g, "\\20").replace(/\"/g, "\\22").replace(/\&/g, "\\26").replace(/\'/g, "\\27").replace(/\//g, "\\2f").replace(/:/g, "\\3a").replace(/</g, "\\3c").replace(/>/g, "\\3e").replace(/@/g, "\\40");
      }, unescapeNode: function unescapeNode(t) {
        return "string" != typeof t ? t : t.replace(/\\20/g, " ").replace(/\\22/g, '"').replace(/\\26/g, "&").replace(/\\27/g, "'").replace(/\\2f/g, "/").replace(/\\3a/g, ":").replace(/\\3c/g, "<").replace(/\\3e/g, ">").replace(/\\40/g, "@").replace(/\\5c/g, "\\");
      }, getNodeFromJid: function getNodeFromJid(t) {
        return t.indexOf("@") < 0 ? t : t.split("@")[0];
      }, getDomainFromJid: function getDomainFromJid(t) {
        var e = a.getBareJidFromJid(t);if (e.indexOf("@") < 0) return e;var n = e.split("@");return n.splice(0, 1), n.join("@");
      }, getResourceFromJid: function getResourceFromJid(t) {
        var e = t.split("/");return e.length < 2 ? null : (e.splice(0, 1), e.join("/"));
      }, getBareJidFromJid: function getBareJidFromJid(t) {
        return t ? t.split("/")[0] : null;
      }, _handleError: function _handleError(t) {
        void 0 !== t.stack && a.fatal(t.stack), t.sourceURL ? a.fatal("error: " + this.handler + " " + t.sourceURL + ":" + t.line + " - " + t.name + ": " + t.message) : t.fileName ? a.fatal("error: " + this.handler + " " + t.fileName + ":" + t.lineNumber + " - " + t.name + ": " + t.message) : a.fatal("error: " + t.message);
      }, log: function log(t, e) {
        switch (t) {case this.LogLevel.DEBUG:case this.LogLevel.INFO:
            break;case this.LogLevel.WARN:
            console.warn(e);break;case this.LogLevel.ERROR:case this.LogLevel.FATAL:
            console.error(e);}
      }, debug: function debug(t) {
        this.log(this.LogLevel.DEBUG, t);
      }, info: function info(t) {
        this.log(this.LogLevel.INFO, t);
      }, warn: function warn(t) {
        this.log(this.LogLevel.WARN, t);
      }, error: function error(t) {
        this.log(this.LogLevel.ERROR, t);
      }, fatal: function fatal(t) {
        this.log(this.LogLevel.FATAL, t);
      }, serialize: function serialize(t) {
        var e;if (!t) return null;"function" == typeof t.tree && (t = t.tree());var n,
            i,
            s = t.nodeName;for (t.getAttribute("_realname") && (s = t.getAttribute("_realname")), e = "<" + s, n = 0; n < t.attributes.length; n++) {
          "_realname" !== t.attributes[n].nodeName && (e += " " + t.attributes[n].nodeName + "='" + a.xmlescape(t.attributes[n].value) + "'");
        }if (t.childNodes.length > 0) {
          for (e += ">", n = 0; n < t.childNodes.length; n++) {
            switch (i = t.childNodes[n], i.nodeType) {case a.ElementType.NORMAL:
                e += a.serialize(i);break;case a.ElementType.TEXT:
                e += a.xmlescape(i.nodeValue);break;case a.ElementType.CDATA:
                e += "<![CDATA[" + i.nodeValue + "]]>";}
          }e += "</" + s + ">";
        } else e += "/>";return e;
      }, _requestId: 0, _connectionPlugins: {}, addConnectionPlugin: function addConnectionPlugin(t, e) {
        a._connectionPlugins[t] = e;
      } }, a.Builder = function (t, e) {
      "presence" !== t && "message" !== t && "iq" !== t || (e && !e.xmlns ? e.xmlns = a.NS.CLIENT : e || (e = { xmlns: a.NS.CLIENT })), this.nodeTree = a.xmlElement(t, e), this.node = this.nodeTree;
    }, a.Builder.prototype = { tree: function tree() {
        return this.nodeTree;
      }, toString: function toString() {
        return a.serialize(this.nodeTree);
      }, up: function up() {
        return this.node = this.node.parentNode, this;
      }, root: function root() {
        return this.node = this.nodeTree, this;
      }, attrs: function attrs(t) {
        for (var e in t) {
          t.hasOwnProperty(e) && (void 0 === t[e] ? this.node.removeAttribute(e) : this.node.setAttribute(e, t[e]));
        }return this;
      }, c: function c(t, e, n) {
        var i = a.xmlElement(t, e, n);return this.node.appendChild(i), "string" != typeof n && "number" != typeof n && (this.node = i), this;
      }, cnode: function cnode(t) {
        var e,
            n = a.xmlGenerator();try {
          e = void 0 !== n.importNode;
        } catch (t) {
          e = !1;
        }var i = e ? n.importNode(t, !0) : a.copyElement(t);return this.node.appendChild(i), this.node = i, this;
      }, t: function t(_t2) {
        var e = a.xmlTextNode(_t2);return this.node.appendChild(e), this;
      }, h: function h(t) {
        var e = document.createElement("body");e.innerHTML = t;for (var n = a.createHtml(e); n.childNodes.length > 0;) {
          this.node.appendChild(n.childNodes[0]);
        }return this;
      } }, a.Handler = function (t, e, n, i, s, r, o) {
      this.handler = t, this.ns = e, this.name = n, this.type = i, this.id = s, this.options = o || { matchBareFromJid: !1, ignoreNamespaceFragment: !1 }, this.options.matchBare && (a.warn('The "matchBare" option is deprecated, use "matchBareFromJid" instead.'), this.options.matchBareFromJid = this.options.matchBare, delete this.options.matchBare), this.options.matchBareFromJid ? this.from = r ? a.getBareJidFromJid(r) : null : this.from = r, this.user = !0;
    }, a.Handler.prototype = { getNamespace: function getNamespace(t) {
        var e = t.getAttribute("xmlns");return e && this.options.ignoreNamespaceFragment && (e = e.split("#")[0]), e;
      }, namespaceMatch: function namespaceMatch(t) {
        var e = !1;if (!this.ns) return !0;var n = this;return a.forEachChild(t, null, function (t) {
          n.getNamespace(t) === n.ns && (e = !0);
        }), e = e || this.getNamespace(t) === this.ns;
      }, isMatch: function isMatch(t) {
        var e = t.getAttribute("from");this.options.matchBareFromJid && (e = a.getBareJidFromJid(e));var n = t.getAttribute("type");return !(!this.namespaceMatch(t) || this.name && !a.isTagEqual(t, this.name) || this.type && (Array.isArray(this.type) ? -1 === this.type.indexOf(n) : n !== this.type) || this.id && t.getAttribute("id") !== this.id || this.from && e !== this.from);
      }, run: function run(t) {
        var e = null;try {
          e = this.handler(t);
        } catch (t) {
          throw a._handleError(t), t;
        }return e;
      }, toString: function toString() {
        return "{Handler: " + this.handler + "(" + this.name + "," + this.id + "," + this.ns + ")}";
      } }, a.TimedHandler = function (t, e) {
      this.period = t, this.handler = e, this.lastCalled = new Date().getTime(), this.user = !0;
    }, a.TimedHandler.prototype = { run: function run() {
        return this.lastCalled = new Date().getTime(), this.handler();
      }, reset: function reset() {
        this.lastCalled = new Date().getTime();
      }, toString: function toString() {
        return "{TimedHandler: " + this.handler + "(" + this.period + ")}";
      } }, a.Connection = function (t, e) {
      this.service = t, this.options = e || {};var i = this.options.protocol || "";0 === t.indexOf("ws:") || 0 === t.indexOf("wss:") || 0 === i.indexOf("ws") ? this._proto = new a.Websocket(this) : this._proto = new a.Bosh(this), this.jid = "", this.domain = null, this.features = null, this._sasl_data = {}, this.do_session = !1, this.do_bind = !1, this.timedHandlers = [], this.handlers = [], this.removeTimeds = [], this.removeHandlers = [], this.addTimeds = [], this.addHandlers = [], this.protocolErrorHandlers = { HTTP: {}, websocket: {} }, this._idleTimeout = null, this._disconnectTimeout = null, this.authenticated = !1, this.connected = !1, this.disconnecting = !1, this.do_authentication = !0, this.paused = !1, this.restored = !1, this._data = [], this._uniqueId = 0, this._sasl_success_handler = null, this._sasl_failure_handler = null, this._sasl_challenge_handler = null, this.maxRetries = 5, this._idleTimeout = setTimeout(function () {
        this._onIdle();
      }.bind(this), 100), n.addCookies(this.options.cookies), this.registerSASLMechanisms(this.options.mechanisms);for (var s in a._connectionPlugins) {
        if (a._connectionPlugins.hasOwnProperty(s)) {
          var r = a._connectionPlugins[s],
              o = function o() {};o.prototype = r, this[s] = new o(), this[s].init(this);
        }
      }
    }, a.Connection.prototype = { reset: function reset() {
        this._proto._reset(), this.do_session = !1, this.do_bind = !1, this.timedHandlers = [], this.handlers = [], this.removeTimeds = [], this.removeHandlers = [], this.addTimeds = [], this.addHandlers = [], this.authenticated = !1, this.connected = !1, this.disconnecting = !1, this.restored = !1, this._data = [], this._requests = [], this._uniqueId = 0;
      }, pause: function pause() {
        this.paused = !0;
      }, resume: function resume() {
        this.paused = !1;
      }, getUniqueId: function getUniqueId(t) {
        var e = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (t) {
          var e = 16 * Math.random() | 0;return ("x" === t ? e : 3 & e | 8).toString(16);
        });return "string" == typeof t || "number" == typeof t ? e + ":" + t : e + "";
      }, addProtocolErrorHandler: function addProtocolErrorHandler(t, e, n) {
        this.protocolErrorHandlers[t][e] = n;
      }, connect: function connect(t, e, n, i, s, r, o) {
        this.jid = t, this.authzid = "", this.authcid = this.jid.split("/")[0], this.pass = e, this.servtype = "xmpp", this.connect_callback = n, this.disconnecting = !1, this.connected = !1, this.authenticated = !1, this.restored = !1, this.domain = a.getDomainFromJid(this.jid), this._changeConnectStatus(a.Status.CONNECTING, null), this._proto._connect(i, s, r);
      }, attach: function attach(t, e, n, i, s, r, o) {
        if (!(this._proto instanceof a.Bosh)) throw { name: "StropheSessionError", message: 'The "attach" method can only be used with a BOSH connection.' };this._proto._attach(t, e, n, i, s, r, o);
      }, restore: function restore(t, e, n, i, s) {
        if (!this._sessionCachingSupported()) throw { name: "StropheSessionError", message: 'The "restore" method can only be used with a BOSH connection.' };this._proto._restore(t, e, n, i, s);
      }, _sessionCachingSupported: function _sessionCachingSupported() {
        if (this._proto instanceof a.Bosh) {
          if (!JSON) return !1;try {
            sessionStorage.setItem("_strophe_", "_strophe_"), sessionStorage.removeItem("_strophe_");
          } catch (t) {
            return !1;
          }return !0;
        }return !1;
      }, xmlInput: function xmlInput(t) {}, xmlOutput: function xmlOutput(t) {}, rawInput: function rawInput(t) {}, rawOutput: function rawOutput(t) {}, nextValidRid: function nextValidRid(t) {}, send: function send(t) {
        if (null !== t) {
          if ("function" == typeof t.sort) for (var e = 0; e < t.length; e++) {
            this._queueData(t[e]);
          } else "function" == typeof t.tree ? this._queueData(t.tree()) : this._queueData(t);this._proto._send();
        }
      }, flush: function flush() {
        clearTimeout(this._idleTimeout), this._onIdle();
      }, sendPresence: function sendPresence(t, e, n, i) {
        var s = null,
            r = this;"function" == typeof t.tree && (t = t.tree());var o = t.getAttribute("id");if (o || (o = this.getUniqueId("sendPresence"), t.setAttribute("id", o)), "function" == typeof e || "function" == typeof n) {
          var a = this.addHandler(function (t) {
            s && r.deleteTimedHandler(s), "error" === t.getAttribute("type") ? n && n(t) : e && e(t);
          }, null, "presence", null, o);i && (s = this.addTimedHandler(i, function () {
            return r.deleteHandler(a), n && n(null), !1;
          }));
        }return this.send(t), o;
      }, sendIQ: function sendIQ(t, e, n, i) {
        var s = null,
            r = this;"function" == typeof t.tree && (t = t.tree());var o = t.getAttribute("id");if (o || (o = this.getUniqueId("sendIQ"), t.setAttribute("id", o)), "function" == typeof e || "function" == typeof n) {
          var a = this.addHandler(function (t) {
            s && r.deleteTimedHandler(s);var i = t.getAttribute("type");if ("result" === i) e && e(t);else {
              if ("error" !== i) throw { name: "StropheError", message: "Got bad IQ type of " + i };n && n(t);
            }
          }, null, "iq", ["error", "result"], o);i && (s = this.addTimedHandler(i, function () {
            return r.deleteHandler(a), n && n(null), !1;
          }));
        }return this.send(t), o;
      }, _queueData: function _queueData(t) {
        if (null === t || !t.tagName || !t.childNodes) throw { name: "StropheError", message: "Cannot queue non-DOMElement." };this._data.push(t);
      }, _sendRestart: function _sendRestart() {
        this._data.push("restart"), this._proto._sendRestart(), this._idleTimeout = setTimeout(function () {
          this._onIdle();
        }.bind(this), 100);
      }, addTimedHandler: function addTimedHandler(t, e) {
        var n = new a.TimedHandler(t, e);return this.addTimeds.push(n), n;
      }, deleteTimedHandler: function deleteTimedHandler(t) {
        this.removeTimeds.push(t);
      }, addHandler: function addHandler(t, e, n, i, s, r, o) {
        var h = new a.Handler(t, e, n, i, s, r, o);return this.addHandlers.push(h), h;
      }, deleteHandler: function deleteHandler(t) {
        this.removeHandlers.push(t);var e = this.addHandlers.indexOf(t);e >= 0 && this.addHandlers.splice(e, 1);
      }, registerSASLMechanisms: function registerSASLMechanisms(t) {
        this.mechanisms = {}, t = t || [a.SASLAnonymous, a.SASLExternal, a.SASLMD5, a.SASLOAuthBearer, a.SASLPlain, a.SASLSHA1], t.forEach(this.registerSASLMechanism.bind(this));
      }, registerSASLMechanism: function registerSASLMechanism(t) {
        this.mechanisms[t.prototype.name] = t;
      }, disconnect: function disconnect(t) {
        if (this._changeConnectStatus(a.Status.DISCONNECTING, t), a.info("Disconnect was called because: " + t), this.connected) {
          var e = !1;this.disconnecting = !0, this.authenticated && (e = o({ xmlns: a.NS.CLIENT, type: "unavailable" })), this._disconnectTimeout = this._addSysTimedHandler(3e3, this._onDisconnectTimeout.bind(this)), this._proto._disconnect(e);
        } else a.info("Disconnect was called before Strophe connected to the server"), this._proto._abortAllRequests(), this._doDisconnect();
      }, _changeConnectStatus: function _changeConnectStatus(t, e) {
        for (var n in a._connectionPlugins) {
          if (a._connectionPlugins.hasOwnProperty(n)) {
            var i = this[n];if (i.statusChanged) try {
              i.statusChanged(t, e);
            } catch (t) {
              a.error(n + " plugin caused an exception changing status: " + t);
            }
          }
        }if (this.connect_callback) try {
          this.connect_callback(t, e);
        } catch (t) {
          a._handleError(t), a.error("User connection callback caused an exception: " + t);
        }
      }, _doDisconnect: function _doDisconnect(t) {
        "number" == typeof this._idleTimeout && clearTimeout(this._idleTimeout), null !== this._disconnectTimeout && (this.deleteTimedHandler(this._disconnectTimeout), this._disconnectTimeout = null), a.info("_doDisconnect was called"), this._proto._doDisconnect(), this.authenticated = !1, this.disconnecting = !1, this.restored = !1, this.handlers = [], this.timedHandlers = [], this.removeTimeds = [], this.removeHandlers = [], this.addTimeds = [], this.addHandlers = [], this._changeConnectStatus(a.Status.DISCONNECTED, t), this.connected = !1;
      }, _dataRecv: function _dataRecv(t, e) {
        a.info("_dataRecv called");var n = this._proto._reqToData(t);if (null !== n) {
          this.xmlInput !== a.Connection.prototype.xmlInput && (n.nodeName === this._proto.strip && n.childNodes.length ? this.xmlInput(n.childNodes[0]) : this.xmlInput(n)), this.rawInput !== a.Connection.prototype.rawInput && (e ? this.rawInput(e) : this.rawInput(a.serialize(n)));for (var i, s; this.removeHandlers.length > 0;) {
            s = this.removeHandlers.pop(), (i = this.handlers.indexOf(s)) >= 0 && this.handlers.splice(i, 1);
          }for (; this.addHandlers.length > 0;) {
            this.handlers.push(this.addHandlers.pop());
          }if (this.disconnecting && this._proto._emptyQueue()) return void this._doDisconnect();var r,
              o,
              h = n.getAttribute("type");if (null !== h && "terminate" === h) {
            if (this.disconnecting) return;return r = n.getAttribute("condition"), o = n.getElementsByTagName("conflict"), null !== r ? ("remote-stream-error" === r && o.length > 0 && (r = "conflict"), this._changeConnectStatus(a.Status.CONNFAIL, r)) : this._changeConnectStatus(a.Status.CONNFAIL, "unknown"), void this._doDisconnect(r);
          }var c = this;a.forEachChild(n, null, function (t) {
            var e, n;for (n = c.handlers, c.handlers = [], e = 0; e < n.length; e++) {
              var i = n[e];try {
                !i.isMatch(t) || !c.authenticated && i.user ? c.handlers.push(i) : i.run(t) && c.handlers.push(i);
              } catch (t) {
                a.warn("Removing Strophe handlers due to uncaught exception: " + t.message);
              }
            }
          });
        }
      }, mechanisms: {}, _connect_cb: function _connect_cb(t, e, n) {
        a.info("_connect_cb was called"), this.connected = !0;var i;try {
          i = this._proto._reqToData(t);
        } catch (t) {
          if ("badformat" !== t) throw t;this._changeConnectStatus(a.Status.CONNFAIL, "bad-format"), this._doDisconnect("bad-format");
        }if (i) {
          this.xmlInput !== a.Connection.prototype.xmlInput && (i.nodeName === this._proto.strip && i.childNodes.length ? this.xmlInput(i.childNodes[0]) : this.xmlInput(i)), this.rawInput !== a.Connection.prototype.rawInput && (n ? this.rawInput(n) : this.rawInput(a.serialize(i)));if (this._proto._connect_cb(i) !== a.Status.CONNFAIL) {
            if (!(i.getElementsByTagNameNS ? i.getElementsByTagNameNS(a.NS.STREAM, "features").length > 0 : i.getElementsByTagName("stream:features").length > 0 || i.getElementsByTagName("features").length > 0)) return void this._proto._no_auth_received(e);var s,
                r,
                o = [],
                h = i.getElementsByTagName("mechanism");if (h.length > 0) for (s = 0; s < h.length; s++) {
              r = a.getText(h[s]), this.mechanisms[r] && o.push(this.mechanisms[r]);
            }if (0 === o.length && 0 === i.getElementsByTagName("auth").length) return void this._proto._no_auth_received(e);!1 !== this.do_authentication && (a.info("calling this.authenticate"), this.authenticate(o));
          }
        }
      }, sortMechanismsByPriority: function sortMechanismsByPriority(t) {
        var e, n, i, s;for (e = 0; e < t.length - 1; ++e) {
          for (i = e, n = e + 1; n < t.length; ++n) {
            t[n].prototype.priority > t[i].prototype.priority && (i = n);
          }i !== e && (s = t[e], t[e] = t[i], t[i] = s);
        }return t;
      }, _attemptSASLAuth: function _attemptSASLAuth(t) {
        a.info("_attemptSASLAuth Enter."), t = this.sortMechanismsByPriority(t || []);var e = 0,
            n = !1;for (e = 0; e < t.length; ++e) {
          if (t[e].prototype.test(this)) {
            this._sasl_success_handler = this._addSysHandler(this._sasl_success_cb.bind(this), null, "success", null, null), this._sasl_failure_handler = this._addSysHandler(this._sasl_failure_cb.bind(this), null, "failure", null, null), this._sasl_challenge_handler = this._addSysHandler(this._sasl_challenge_cb.bind(this), null, "challenge", null, null), this._sasl_mechanism = new t[e](), this._sasl_mechanism.onStart(this), a.info("building auth tag");var s = i("auth", { xmlns: a.NS.SASL, mechanism: this._sasl_mechanism.name });if (this._sasl_mechanism.isClientFirst) {
              var r = this._sasl_mechanism.onChallenge(this, null);s.t(btoa(r));
            }this.send(s.tree()), n = !0;break;
          }
        }return n;
      }, _attemptLegacyAuth: function _attemptLegacyAuth() {
        null === a.getNodeFromJid(this.jid) ? (this._changeConnectStatus(a.Status.CONNFAIL, "x-strophe-bad-non-anon-jid"), this.disconnect("x-strophe-bad-non-anon-jid")) : (this._changeConnectStatus(a.Status.AUTHENTICATING, null), this._addSysHandler(this._auth1_cb.bind(this), null, null, null, "_auth_1"), this.send(r({ type: "get", to: this.domain, id: "_auth_1" }).c("query", { xmlns: a.NS.AUTH }).c("username", {}).t(a.getNodeFromJid(this.jid)).tree()));
      }, authenticate: function authenticate(t) {
        this._attemptSASLAuth(t) || this._attemptLegacyAuth();
      }, _sasl_challenge_cb: function _sasl_challenge_cb(t) {
        var e = atob(a.getText(t)),
            n = this._sasl_mechanism.onChallenge(this, e),
            s = i("response", { xmlns: a.NS.SASL });return "" !== n && s.t(btoa(n)), this.send(s.tree()), !0;
      }, _auth1_cb: function _auth1_cb(t) {
        var e = r({ type: "set", id: "_auth_2" }).c("query", { xmlns: a.NS.AUTH }).c("username", {}).t(a.getNodeFromJid(this.jid)).up().c("password").t(this.pass);return a.getResourceFromJid(this.jid) || (this.jid = a.getBareJidFromJid(this.jid) + "/strophe"), e.up().c("resource", {}).t(a.getResourceFromJid(this.jid)), this._addSysHandler(this._auth2_cb.bind(this), null, null, null, "_auth_2"), this.send(e.tree()), !1;
      }, _sasl_success_cb: function _sasl_success_cb(t) {
        if (this._sasl_data["server-signature"]) {
          var e,
              n = atob(a.getText(t)),
              i = /([a-z]+)=([^,]+)(,|$)/,
              s = n.match(i);if ("v" === s[1] && (e = s[2]), e !== this._sasl_data["server-signature"]) return this.deleteHandler(this._sasl_failure_handler), this._sasl_failure_handler = null, this._sasl_challenge_handler && (this.deleteHandler(this._sasl_challenge_handler), this._sasl_challenge_handler = null), this._sasl_data = {}, this._sasl_failure_cb(null);
        }a.info("SASL authentication succeeded."), this._sasl_mechanism && this._sasl_mechanism.onSuccess(), this.deleteHandler(this._sasl_failure_handler), this._sasl_failure_handler = null, this._sasl_challenge_handler && (this.deleteHandler(this._sasl_challenge_handler), this._sasl_challenge_handler = null);var r = [],
            o = function o(t, e) {
          for (; t.length;) {
            this.deleteHandler(t.pop());
          }return this._sasl_auth1_cb.bind(this)(e), !1;
        };return r.push(this._addSysHandler(function (t) {
          o.bind(this)(r, t);
        }.bind(this), null, "stream:features", null, null)), r.push(this._addSysHandler(function (t) {
          o.bind(this)(r, t);
        }.bind(this), a.NS.STREAM, "features", null, null)), this._sendRestart(), !1;
      }, _sasl_auth1_cb: function _sasl_auth1_cb(t) {
        this.features = t;var e, n;for (e = 0; e < t.childNodes.length; e++) {
          n = t.childNodes[e], "bind" === n.nodeName && (this.do_bind = !0), "session" === n.nodeName && (this.do_session = !0);
        }if (!this.do_bind) return this._changeConnectStatus(a.Status.AUTHFAIL, null), !1;this._addSysHandler(this._sasl_bind_cb.bind(this), null, null, null, "_bind_auth_2");var i = a.getResourceFromJid(this.jid);return i ? this.send(r({ type: "set", id: "_bind_auth_2" }).c("bind", { xmlns: a.NS.BIND }).c("resource", {}).t(i).tree()) : this.send(r({ type: "set", id: "_bind_auth_2" }).c("bind", { xmlns: a.NS.BIND }).tree()), !1;
      }, _sasl_bind_cb: function _sasl_bind_cb(t) {
        if (a.info("_sasl_bind_cb Enter."), "error" === t.getAttribute("type")) {
          a.info("_sasl_bind_cb failed."), a.info("SASL binding failed.");var e,
              n = t.getElementsByTagName("conflict");return n.length > 0 && (e = "conflict"), this._changeConnectStatus(a.Status.AUTHFAIL, e), !1;
        }var i,
            s = t.getElementsByTagName("bind");if (!(s.length > 0)) return a.info("SASL binding failed."), a.info("SASL binding failed."), this._changeConnectStatus(a.Status.AUTHFAIL, null), !1;i = s[0].getElementsByTagName("jid"), i.length > 0 && (a.info("_sasl_bind_cb jidNode:", i), this.jid = a.getText(i[0]), this.do_session ? (this._addSysHandler(this._sasl_session_cb.bind(this), null, null, null, "_session_auth_2"), this.send(r({ type: "set", id: "_session_auth_2" }).c("session", { xmlns: a.NS.SESSION }).tree())) : (a.info("_sasl_bind_cb turnning connected..."), this.authenticated = !0, this._changeConnectStatus(a.Status.CONNECTED, null)));
      }, _sasl_session_cb: function _sasl_session_cb(t) {
        if ("result" === t.getAttribute("type")) this.authenticated = !0, this._changeConnectStatus(a.Status.CONNECTED, null);else if ("error" === t.getAttribute("type")) return a.info("Session creation failed."), this._changeConnectStatus(a.Status.AUTHFAIL, null), !1;return !1;
      }, _sasl_failure_cb: function _sasl_failure_cb(t) {
        return this._sasl_success_handler && (this.deleteHandler(this._sasl_success_handler), this._sasl_success_handler = null), this._sasl_challenge_handler && (this.deleteHandler(this._sasl_challenge_handler), this._sasl_challenge_handler = null), this._sasl_mechanism && this._sasl_mechanism.onFailure(), this._changeConnectStatus(a.Status.AUTHFAIL, null), !1;
      }, _auth2_cb: function _auth2_cb(t) {
        return "result" === t.getAttribute("type") ? (this.authenticated = !0, this._changeConnectStatus(a.Status.CONNECTED, null)) : "error" === t.getAttribute("type") && (this._changeConnectStatus(a.Status.AUTHFAIL, null), this.disconnect("authentication failed")), !1;
      }, _addSysTimedHandler: function _addSysTimedHandler(t, e) {
        var n = new a.TimedHandler(t, e);return n.user = !1, this.addTimeds.push(n), n;
      }, _addSysHandler: function _addSysHandler(t, e, n, i, s) {
        var r = new a.Handler(t, e, n, i, s);return r.user = !1, this.addHandlers.push(r), r;
      }, _onDisconnectTimeout: function _onDisconnectTimeout() {
        return a.info("_onDisconnectTimeout was called"), this._changeConnectStatus(a.Status.CONNTIMEOUT, null), this._proto._onDisconnectTimeout(), this._doDisconnect(), !1;
      }, _onIdle: function _onIdle() {
        for (var t, e, n, i; this.addTimeds.length > 0;) {
          this.timedHandlers.push(this.addTimeds.pop());
        }for (; this.removeTimeds.length > 0;) {
          e = this.removeTimeds.pop(), (t = this.timedHandlers.indexOf(e)) >= 0 && this.timedHandlers.splice(t, 1);
        }var s = new Date().getTime();for (i = [], t = 0; t < this.timedHandlers.length; t++) {
          e = this.timedHandlers[t], !this.authenticated && e.user || (n = e.lastCalled + e.period, n - s <= 0 ? e.run() && i.push(e) : i.push(e));
        }this.timedHandlers = i, clearTimeout(this._idleTimeout), this._proto._onIdle(), this.connected && (this._idleTimeout = setTimeout(function () {
          this._onIdle();
        }.bind(this), 100));
      } }, a.SASLMechanism = function (t, e, n) {
      this.name = t, this.isClientFirst = e, this.priority = n;
    }, a.SASLMechanism.prototype = { test: function test(t) {
        return !0;
      }, onStart: function onStart(t) {
        this._connection = t;
      }, onChallenge: function onChallenge(t, e) {
        throw new Error("You should implement challenge handling!");
      }, onFailure: function onFailure() {
        this._connection = null;
      }, onSuccess: function onSuccess() {
        this._connection = null;
      } }, a.SASLAnonymous = function () {}, a.SASLAnonymous.prototype = new a.SASLMechanism("ANONYMOUS", !1, 20), a.SASLAnonymous.prototype.test = function (t) {
      return null === t.authcid;
    }, a.SASLPlain = function () {}, a.SASLPlain.prototype = new a.SASLMechanism("PLAIN", !0, 30), a.SASLPlain.prototype.test = function (t) {
      return null !== t.authcid;
    }, a.SASLPlain.prototype.onChallenge = function (t) {
      var e = t.authzid;return e += "\0", e += t.authcid, e += "\0", e += t.pass, n.utf16to8(e);
    }, a.SASLSHA1 = function () {}, a.SASLSHA1.prototype = new a.SASLMechanism("SCRAM-SHA-1", !0, 50), a.SASLSHA1.prototype.test = function (t) {
      return null !== t.authcid;
    }, a.SASLSHA1.prototype.onChallenge = function (i, s, r) {
      var o = r || e.hexdigest(1234567890 * Math.random()),
          a = "n=" + n.utf16to8(i.authcid);return a += ",r=", a += o, i._sasl_data.cnonce = o, i._sasl_data["client-first-message-bare"] = a, a = "n,," + a, this.onChallenge = function (e, i) {
        for (var s, r, o, a, h, c, u, l, d, _, f, p, m = "c=biws,", g = e._sasl_data["client-first-message-bare"] + "," + i + ",", S = e._sasl_data.cnonce, b = /([a-z]+)=([^,]+)(,|$)/; i.match(b);) {
          var v = i.match(b);switch (i = i.replace(v[0], ""), v[1]) {case "r":
              s = v[2];break;case "s":
              r = v[2];break;case "i":
              o = v[2];}
        }if (s.substr(0, S.length) !== S) return e._sasl_data = {}, e._sasl_failure_cb();for (m += "r=" + s, g += m, r = atob(r), r += "\0\0\0", d = n.utf16to8(e.pass), a = c = t.core_hmac_sha1(d, r), u = 1; u < o; u++) {
          for (h = t.core_hmac_sha1(d, t.binb2str(c)), l = 0; l < 5; l++) {
            a[l] ^= h[l];
          }c = h;
        }for (a = t.binb2str(a), _ = t.core_hmac_sha1(a, "Client Key"), f = t.str_hmac_sha1(a, "Server Key"), p = t.core_hmac_sha1(t.str_sha1(t.binb2str(_)), g), e._sasl_data["server-signature"] = t.b64_hmac_sha1(f, g), l = 0; l < 5; l++) {
          _[l] ^= p[l];
        }return m += ",p=" + btoa(t.binb2str(_));
      }.bind(this), a;
    }, a.SASLMD5 = function () {}, a.SASLMD5.prototype = new a.SASLMechanism("DIGEST-MD5", !1, 40), a.SASLMD5.prototype.test = function (t) {
      return null !== t.authcid;
    }, a.SASLMD5.prototype._quote = function (t) {
      return '"' + t.replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"';
    }, a.SASLMD5.prototype.onChallenge = function (t, i, s) {
      for (var r, o = /([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/, a = s || e.hexdigest("" + 1234567890 * Math.random()), h = "", c = null, u = ""; i.match(o);) {
        switch (r = i.match(o), i = i.replace(r[0], ""), r[2] = r[2].replace(/^"(.+)"$/, "$1"), r[1]) {case "realm":
            h = r[2];break;case "nonce":
            u = r[2];break;case "qop":
            r[2];break;case "host":
            c = r[2];}
      }var l = t.servtype + "/" + t.domain;null !== c && (l = l + "/" + c);var d = n.utf16to8(t.authcid + ":" + h + ":" + this._connection.pass),
          _ = e.hash(d) + ":" + u + ":" + a,
          f = "AUTHENTICATE:" + l,
          p = "";return p += "charset=utf-8,", p += "username=" + this._quote(n.utf16to8(t.authcid)) + ",", p += "realm=" + this._quote(h) + ",", p += "nonce=" + this._quote(u) + ",", p += "nc=00000001,", p += "cnonce=" + this._quote(a) + ",", p += "digest-uri=" + this._quote(l) + ",", p += "response=" + e.hexdigest(e.hexdigest(_) + ":" + u + ":00000001:" + a + ":auth:" + e.hexdigest(f)) + ",", p += "qop=auth", this.onChallenge = function () {
        return "";
      }, p;
    }, a.SASLOAuthBearer = function () {}, a.SASLOAuthBearer.prototype = new a.SASLMechanism("OAUTHBEARER", !0, 60), a.SASLOAuthBearer.prototype.test = function (t) {
      return null !== t.pass;
    }, a.SASLOAuthBearer.prototype.onChallenge = function (t) {
      var e = "n,";return null !== t.authcid && (e = e + "a=" + t.authzid), e += ",", e += "", e += "auth=Bearer ", e += t.pass, e += "", e += "", n.utf16to8(e);
    }, a.SASLExternal = function () {}, a.SASLExternal.prototype = new a.SASLMechanism("EXTERNAL", !0, 10), a.SASLExternal.prototype.onChallenge = function (t) {
      return t.authcid === t.authzid ? "" : t.authzid;
    }, { Strophe: a, $build: i, $iq: r, $msg: s, $pres: o, SHA1: t, MD5: e, b64_hmac_sha1: t.b64_hmac_sha1, b64_sha1: t.b64_sha1, str_hmac_sha1: t.str_hmac_sha1, str_sha1: t.str_sha1 };
  }), function (t, e) {
    if ("function" != typeof n || !n.amd) return e(Strophe, $build);n("strophe-bosh", ["strophe-core"], function (t) {
      return e(t.Strophe, t.$build);
    });
  }(0, function (t, e) {
    return t.Request = function (e, n, i, s) {
      this.id = ++t._requestId, this.xmlData = e, this.data = t.serialize(e), this.origFunc = n, this.func = n, this.rid = i, this.date = NaN, this.sends = s || 0, this.abort = !1, this.dead = null, this.age = function () {
        return this.date ? (new Date() - this.date) / 1e3 : 0;
      }, this.timeDead = function () {
        return this.dead ? (new Date() - this.dead) / 1e3 : 0;
      }, this.xhr = this._newXHR();
    }, t.Request.prototype = { getResponse: function getResponse() {
        var e = null;if (this.xhr.responseXML && this.xhr.responseXML.documentElement) {
          if (e = this.xhr.responseXML.documentElement, "parsererror" === e.tagName) throw t.error("invalid response received"), t.error("responseText: " + this.xhr.responseText), t.error("responseXML: " + t.serialize(this.xhr.responseXML)), "parsererror";
        } else if (this.xhr.responseText) throw t.error("invalid response received"), t.error("responseText: " + this.xhr.responseText), "badformat";return e;
      }, _newXHR: function _newXHR() {
        var t = null;return window.XMLHttpRequest ? (t = new XMLHttpRequest(), t.overrideMimeType && t.overrideMimeType("text/xml; charset=utf-8")) : window.ActiveXObject && (t = new ActiveXObject("Microsoft.XMLHTTP")), t.onreadystatechange = this.func.bind(null, this), t;
      } }, t.Bosh = function (t) {
      this._conn = t, this.rid = Math.floor(4294967295 * Math.random()), this.sid = null, this.hold = 1, this.wait = 60, this.window = 5, this.errors = 0, this.inactivity = null, this._requests = [];
    }, t.Bosh.prototype = { strip: null, _buildBody: function _buildBody() {
        var n = e("body", { rid: this.rid++, xmlns: t.NS.HTTPBIND });return null !== this.sid && n.attrs({ sid: this.sid }), this._conn.options.keepalive && this._conn._sessionCachingSupported() && this._cacheSession(), n;
      }, _reset: function _reset() {
        this.rid = Math.floor(4294967295 * Math.random()), this.sid = null, this.errors = 0, this._conn._sessionCachingSupported() && window.sessionStorage.removeItem("strophe-bosh-session"), this._conn.nextValidRid(this.rid);
      }, _connect: function _connect(e, n, i) {
        this.wait = e || this.wait, this.hold = n || this.hold, this.errors = 0;var s = this._buildBody().attrs({ to: this._conn.domain, "xml:lang": "en", wait: this.wait, hold: this.hold, content: "text/xml; charset=utf-8", ver: "1.6", "xmpp:version": "1.0", "xmlns:xmpp": t.NS.BOSH });i && s.attrs({ route: i });var r = this._conn._connect_cb;this._requests.push(new t.Request(s.tree(), this._onRequestStateChange.bind(this, r.bind(this._conn)), s.tree().getAttribute("rid"))), this._throttledRequestHandler();
      }, _attach: function _attach(e, n, i, s, r, o, a) {
        this._conn.jid = e, this.sid = n, this.rid = i, this._conn.connect_callback = s, this._conn.domain = t.getDomainFromJid(this._conn.jid), this._conn.authenticated = !0, this._conn.connected = !0, this.wait = r || this.wait, this.hold = o || this.hold, this.window = a || this.window, this._conn._changeConnectStatus(t.Status.ATTACHED, null);
      }, _restore: function _restore(e, n, i, s, r) {
        var o = JSON.parse(window.sessionStorage.getItem("strophe-bosh-session"));if (!(void 0 !== o && null !== o && o.rid && o.sid && o.jid && (void 0 === e || null === e || t.getBareJidFromJid(o.jid) === t.getBareJidFromJid(e) || null === t.getNodeFromJid(e) && t.getDomainFromJid(o.jid) === e))) throw { name: "StropheSessionError", message: "_restore: no restoreable session." };this._conn.restored = !0, this._attach(o.jid, o.sid, o.rid, n, i, s, r);
      }, _cacheSession: function _cacheSession() {
        this._conn.authenticated ? this._conn.jid && this.rid && this.sid && window.sessionStorage.setItem("strophe-bosh-session", JSON.stringify({ jid: this._conn.jid, rid: this.rid, sid: this.sid })) : window.sessionStorage.removeItem("strophe-bosh-session");
      }, _connect_cb: function _connect_cb(e) {
        var n,
            i,
            s = e.getAttribute("type");if (null !== s && "terminate" === s) return n = e.getAttribute("condition"), t.error("BOSH-Connection failed: " + n), i = e.getElementsByTagName("conflict"), null !== n ? ("remote-stream-error" === n && i.length > 0 && (n = "conflict"), this._conn._changeConnectStatus(t.Status.CONNFAIL, n)) : this._conn._changeConnectStatus(t.Status.CONNFAIL, "unknown"), this._conn._doDisconnect(n), t.Status.CONNFAIL;this.sid || (this.sid = e.getAttribute("sid"));var r = e.getAttribute("requests");r && (this.window = parseInt(r, 10));var o = e.getAttribute("hold");o && (this.hold = parseInt(o, 10));var a = e.getAttribute("wait");a && (this.wait = parseInt(a, 10));var h = e.getAttribute("inactivity");h && (this.inactivity = parseInt(h, 10));
      }, _disconnect: function _disconnect(t) {
        this._sendTerminate(t);
      }, _doDisconnect: function _doDisconnect() {
        this.sid = null, this.rid = Math.floor(4294967295 * Math.random()), this._conn._sessionCachingSupported() && window.sessionStorage.removeItem("strophe-bosh-session"), this._conn.nextValidRid(this.rid);
      }, _emptyQueue: function _emptyQueue() {
        return 0 === this._requests.length;
      }, _callProtocolErrorHandlers: function _callProtocolErrorHandlers(t) {
        var e,
            n = this._getRequestStatus(t);(e = this._conn.protocolErrorHandlers.HTTP[n]) && e.call(this, n);
      }, _hitError: function _hitError(e) {
        this.errors++, t.warn("request errored, status: " + e + ", number of errors: " + this.errors), this.errors > 4 && this._conn._onDisconnectTimeout();
      }, _no_auth_received: function _no_auth_received(e) {
        e = e ? e.bind(this._conn) : this._conn._connect_cb.bind(this._conn);var n = this._buildBody();this._requests.push(new t.Request(n.tree(), this._onRequestStateChange.bind(this, e.bind(this._conn)), n.tree().getAttribute("rid"))), this._throttledRequestHandler();
      }, _onDisconnectTimeout: function _onDisconnectTimeout() {
        this._abortAllRequests();
      }, _abortAllRequests: function _abortAllRequests() {
        for (var t; this._requests.length > 0;) {
          t = this._requests.pop(), t.abort = !0, t.xhr.abort(), t.xhr.onreadystatechange = function () {};
        }
      }, _onIdle: function _onIdle() {
        var e = this._conn._data;if (this._conn.authenticated && 0 === this._requests.length && 0 === e.length && !this._conn.disconnecting && (t.info("no requests during idle cycle, sending blank request"), e.push(null)), !this._conn.paused) {
          if (this._requests.length < 2 && e.length > 0) {
            for (var n = this._buildBody(), i = 0; i < e.length; i++) {
              null !== e[i] && ("restart" === e[i] ? n.attrs({ to: this._conn.domain, "xml:lang": "en", "xmpp:restart": "true", "xmlns:xmpp": t.NS.BOSH }) : n.cnode(e[i]).up());
            }delete this._conn._data, this._conn._data = [], this._requests.push(new t.Request(n.tree(), this._onRequestStateChange.bind(this, this._conn._dataRecv.bind(this._conn)), n.tree().getAttribute("rid"))), this._throttledRequestHandler();
          }if (this._requests.length > 0) {
            var s = this._requests[0].age();null !== this._requests[0].dead && this._requests[0].timeDead() > Math.floor(t.SECONDARY_TIMEOUT * this.wait) && this._throttledRequestHandler(), s > Math.floor(t.TIMEOUT * this.wait) && (t.warn("Request " + this._requests[0].id + " timed out, over " + Math.floor(t.TIMEOUT * this.wait) + " seconds since last activity"), this._throttledRequestHandler());
          }
        }
      }, _getRequestStatus: function _getRequestStatus(e, n) {
        var i;if (4 === e.xhr.readyState) try {
          i = e.xhr.status;
        } catch (e) {
          t.error("Caught an error while retrieving a request's status, reqStatus: " + i);
        }return void 0 === i && (i = "number" == typeof n ? n : 0), i;
      }, _onRequestStateChange: function _onRequestStateChange(e, n) {
        if (t.debug("request id " + n.id + "." + n.sends + " state changed to " + n.xhr.readyState), n.abort) return void (n.abort = !1);if (4 === n.xhr.readyState) {
          var i = this._getRequestStatus(n);if (this.disconnecting && i >= 400) return this._hitError(i), void this._callProtocolErrorHandlers(n);var s = i > 0 && i < 500,
              r = n.sends > this._conn.maxRetries;if ((s || r) && (this._removeRequest(n), t.debug("request id " + n.id + " should now be removed")), 200 === i) {
            var o = this._requests[0] === n;(this._requests[1] === n || o && this._requests.length > 0 && this._requests[0].age() > Math.floor(t.SECONDARY_TIMEOUT * this.wait)) && this._restartRequest(0), this._conn.nextValidRid(Number(n.rid) + 1), t.debug("request id " + n.id + "." + n.sends + " got 200"), e(n), this.errors = 0;
          } else 0 === i || i >= 400 && i < 600 || i >= 12e3 ? (t.error("request id " + n.id + "." + n.sends + " error " + i + " happened"), this._hitError(i), this._callProtocolErrorHandlers(n), i >= 400 && i < 500 && (this._conn._changeConnectStatus(t.Status.DISCONNECTING, null), this._conn._doDisconnect())) : t.error("request id " + n.id + "." + n.sends + " error " + i + " happened");s || r ? r && !this._conn.connected && this._conn._changeConnectStatus(t.Status.CONNFAIL, "giving-up") : this._throttledRequestHandler();
        }
      }, _processRequest: function _processRequest(e) {
        var n = this,
            i = this._requests[e],
            s = this._getRequestStatus(i, -1);if (i.sends > this._conn.maxRetries) return void this._conn._onDisconnectTimeout();var r = i.age(),
            o = !isNaN(r) && r > Math.floor(t.TIMEOUT * this.wait),
            a = null !== i.dead && i.timeDead() > Math.floor(t.SECONDARY_TIMEOUT * this.wait),
            h = 4 === i.xhr.readyState && (s < 1 || s >= 500);if ((o || a || h) && (a && t.error("Request " + this._requests[e].id + " timed out (secondary), restarting"), i.abort = !0, i.xhr.abort(), i.xhr.onreadystatechange = function () {}, this._requests[e] = new t.Request(i.xmlData, i.origFunc, i.rid, i.sends), i = this._requests[e]), 0 === i.xhr.readyState) {
          t.debug("request id " + i.id + "." + i.sends + " posting");try {
            var c = this._conn.options.contentType || "text/xml; charset=utf-8";i.xhr.open("POST", this._conn.service, !this._conn.options.sync), void 0 !== i.xhr.setRequestHeader && i.xhr.setRequestHeader("Content-Type", c), this._conn.options.withCredentials && (i.xhr.withCredentials = !0);
          } catch (e) {
            return t.error("XHR open failed: " + e.toString()), this._conn.connected || this._conn._changeConnectStatus(t.Status.CONNFAIL, "bad-service"), void this._conn.disconnect();
          }var u = function u() {
            if (i.date = new Date(), n._conn.options.customHeaders) {
              var t = n._conn.options.customHeaders;for (var e in t) {
                t.hasOwnProperty(e) && i.xhr.setRequestHeader(e, t[e]);
              }
            }i.xhr.send(i.data);
          };if (i.sends > 1) {
            var l = 1e3 * Math.min(Math.floor(t.TIMEOUT * this.wait), Math.pow(i.sends, 3));setTimeout(function () {
              u();
            }, l);
          } else u();i.sends++, this._conn.xmlOutput !== t.Connection.prototype.xmlOutput && (i.xmlData.nodeName === this.strip && i.xmlData.childNodes.length ? this._conn.xmlOutput(i.xmlData.childNodes[0]) : this._conn.xmlOutput(i.xmlData)), this._conn.rawOutput !== t.Connection.prototype.rawOutput && this._conn.rawOutput(i.data);
        } else t.debug("_processRequest: " + (0 === e ? "first" : "second") + " request has readyState of " + i.xhr.readyState);
      }, _removeRequest: function _removeRequest(e) {
        t.debug("removing request");var n;for (n = this._requests.length - 1; n >= 0; n--) {
          e === this._requests[n] && this._requests.splice(n, 1);
        }e.xhr.onreadystatechange = function () {}, this._throttledRequestHandler();
      }, _restartRequest: function _restartRequest(t) {
        var e = this._requests[t];null === e.dead && (e.dead = new Date()), this._processRequest(t);
      }, _reqToData: function _reqToData(t) {
        try {
          return t.getResponse();
        } catch (t) {
          if ("parsererror" !== t) throw t;this._conn.disconnect("strophe-parsererror");
        }
      }, _sendTerminate: function _sendTerminate(e) {
        t.info("_sendTerminate was called");var n = this._buildBody().attrs({ type: "terminate" });e && n.cnode(e.tree());var i = new t.Request(n.tree(), this._onRequestStateChange.bind(this, this._conn._dataRecv.bind(this._conn)), n.tree().getAttribute("rid"));this._requests.push(i), this._throttledRequestHandler();
      }, _send: function _send() {
        clearTimeout(this._conn._idleTimeout), this._throttledRequestHandler(), this._conn._idleTimeout = setTimeout(function () {
          this._onIdle();
        }.bind(this._conn), 100);
      }, _sendRestart: function _sendRestart() {
        this._throttledRequestHandler(), clearTimeout(this._conn._idleTimeout);
      }, _throttledRequestHandler: function _throttledRequestHandler() {
        this._requests ? t.debug("_throttledRequestHandler called with " + this._requests.length + " requests") : t.debug("_throttledRequestHandler called with undefined requests"), this._requests && 0 !== this._requests.length && (this._requests.length > 0 && this._processRequest(0), this._requests.length > 1 && Math.abs(this._requests[0].rid - this._requests[1].rid) < this.window && this._processRequest(1));
      } }, t;
  }), function (t, e) {
    if ("function" != typeof n || !n.amd) return e(Strophe, $build);n("strophe-websocket", ["strophe-core"], function (t) {
      return e(t.Strophe, t.$build);
    });
  }(0, function (t, e) {
    return t.Websocket = function (t) {
      this._conn = t, this.strip = "wrapper";var e = t.service;if (0 !== e.indexOf("ws:") && 0 !== e.indexOf("wss:")) {
        var n = "";"ws" === t.options.protocol && "https:" !== window.location.protocol ? n += "ws" : n += "wss", n += "://" + window.location.host, 0 !== e.indexOf("/") ? n += window.location.pathname + e : n += e, t.service = n;
      }
    }, t.Websocket.prototype = { _buildStream: function _buildStream() {
        return e("open", { xmlns: t.NS.FRAMING, to: this._conn.domain, version: "1.0" });
      }, _check_streamerror: function _check_streamerror(e, n) {
        var i;if (i = e.getElementsByTagNameNS ? e.getElementsByTagNameNS(t.NS.STREAM, "error") : e.getElementsByTagName("stream:error"), 0 === i.length) return !1;for (var s = i[0], r = "", o = "", a = 0; a < s.childNodes.length; a++) {
          var h = s.childNodes[a];if ("urn:ietf:params:xml:ns:xmpp-streams" !== h.getAttribute("xmlns")) break;"text" === h.nodeName ? o = h.textContent : r = h.nodeName;
        }var c = "WebSocket stream error: ";return c += r || "unknown", o && (c += " - " + o), t.error(c), this._conn._changeConnectStatus(n, r), this._conn._doDisconnect(), !0;
      }, _reset: function _reset() {}, _connect: function _connect() {
        this._closeSocket(), this.socket = new WebSocket(this._conn.service, "xmpp"), this.socket.onopen = this._onOpen.bind(this), this.socket.onerror = this._onError.bind(this), this.socket.onclose = this._onClose.bind(this), this.socket.onmessage = this._connect_cb_wrapper.bind(this);
      }, _connect_cb: function _connect_cb(e) {
        if (this._check_streamerror(e, t.Status.CONNFAIL)) return t.Status.CONNFAIL;
      }, _handleStreamStart: function _handleStreamStart(e) {
        var n = !1,
            i = e.getAttribute("xmlns");"string" != typeof i ? n = "Missing xmlns in <open />" : i !== t.NS.FRAMING && (n = "Wrong xmlns in <open />: " + i);var s = e.getAttribute("version");return "string" != typeof s ? n = "Missing version in <open />" : "1.0" !== s && (n = "Wrong version in <open />: " + s), !n || (this._conn._changeConnectStatus(t.Status.CONNFAIL, n), this._conn._doDisconnect(), !1);
      }, _connect_cb_wrapper: function _connect_cb_wrapper(e) {
        if (t.info("_connect_cb_wrapper message", e), 0 === e.data.indexOf("<open ") || 0 === e.data.indexOf("<?xml")) {
          t.info("websocket connect cb on open tag");var n = e.data.replace(/^(<\?.*?\?>\s*)*/, "");if ("" === n) return;var i = new DOMParser().parseFromString(n, "text/xml").documentElement;this._conn.xmlInput(i), this._conn.rawInput(e.data), this._handleStreamStart(i) && this._connect_cb(i);
        } else if (0 === e.data.indexOf("<close ")) {
          t.info("websocket connect cb on close tag"), this._conn.rawInput(e.data), this._conn.xmlInput(e);var s = e.getAttribute("see-other-uri");s ? (this._conn._changeConnectStatus(t.Status.REDIRECT, "Received see-other-uri, resetting connection"), this._conn.reset(), this._conn.service = s, this._connect()) : (this._conn._changeConnectStatus(t.Status.CONNFAIL, "Received closing stream"), this._conn._doDisconnect());
        } else {
          t.info("websocket connect cb on other state!");var r = this._streamWrap(e.data),
              o = new DOMParser().parseFromString(r, "text/xml").documentElement;this.socket.onmessage = this._onMessage.bind(this), this._conn._connect_cb(o, null, e.data);
        }
      }, _disconnect: function _disconnect(n) {
        if (this.socket && this.socket.readyState !== WebSocket.CLOSED) {
          n && this._conn.send(n);var i = e("close", { xmlns: t.NS.FRAMING });this._conn.xmlOutput(i);var s = t.serialize(i);this._conn.rawOutput(s);try {
            this.socket.send(s);
          } catch (e) {
            t.info("Couldn't send <close /> tag.");
          }
        }this._conn._doDisconnect();
      }, _doDisconnect: function _doDisconnect() {
        t.info("WebSockets _doDisconnect was called"), this._closeSocket();
      }, _streamWrap: function _streamWrap(t) {
        return "<wrapper>" + t + "</wrapper>";
      }, _closeSocket: function _closeSocket() {
        if (this.socket) try {
          this.socket.close();
        } catch (t) {}this.socket = null;
      }, _emptyQueue: function _emptyQueue() {
        return !0;
      }, _onClose: function _onClose(e) {
        this._conn.connected && !this._conn.disconnecting ? (t.error("Websocket closed unexpectedly"), this._conn._doDisconnect(e)) : e && 1006 === e.code && !this._conn.connected && this.socket ? (t.error("Websocket closed unexcectedly"), this._conn._changeConnectStatus(t.Status.CONNFAIL, "The WebSocket connection could not be established or was disconnected."), this._conn._doDisconnect(e)) : t.info("Websocket closed");
      }, _no_auth_received: function _no_auth_received(e) {
        t.error("Server did not send any auth methods"), this._conn._changeConnectStatus(t.Status.CONNFAIL, "Server did not send any auth methods"), e && (e = e.bind(this._conn))(), this._conn._doDisconnect();
      }, _onDisconnectTimeout: function _onDisconnectTimeout() {}, _abortAllRequests: function _abortAllRequests() {}, _onError: function _onError(e) {
        t.error("Websocket error " + e), this._conn._changeConnectStatus(t.Status.CONNFAIL, "The WebSocket connection could not be established or was disconnected."), this._disconnect();
      }, _onIdle: function _onIdle() {
        var e = this._conn._data;if (e.length > 0 && !this._conn.paused) {
          for (var n = 0; n < e.length; n++) {
            if (null !== e[n]) {
              var i, s;i = "restart" === e[n] ? this._buildStream().tree() : e[n], s = t.serialize(i), this._conn.xmlOutput(i), this._conn.rawOutput(s), t.info("websocket sending data:", s), this.socket.send(s);
            }
          }this._conn._data = [];
        }
      }, _onMessage: function _onMessage(e) {
        if (t.info("_onMessage message", e), e && e.data) {
          var n = _typeof(e.data);if (t.info("typeof message.data:", n), "string" !== n) {
            var i = new FileReader();i.onload = function () {
              t.info(i.result);
            }, i.readAsText(e.data);
          }
        }var s,
            r,
            o = '<close xmlns="urn:ietf:params:xml:ns:xmpp-framing" />';if (e.data === o) return t.info("websocket meet close tag..."), this._conn.rawInput(o), this._conn.xmlInput(e), void (this._conn.disconnecting || this._conn._doDisconnect());if (0 === e.data.search("<open ")) {
          if (s = new DOMParser().parseFromString(e.data, "text/xml").documentElement, !this._handleStreamStart(s)) return;
        } else r = this._streamWrap(e.data), s = new DOMParser().parseFromString(r, "text/xml").documentElement;return this._check_streamerror(s, t.Status.ERROR) ? void 0 : this._conn.disconnecting && "presence" === s.firstChild.nodeName && "unavailable" === s.firstChild.getAttribute("type") ? (this._conn.xmlInput(s), void this._conn.rawInput(t.serialize(s))) : void this._conn._dataRecv(s, e.data);
      }, _onOpen: function _onOpen() {
        t.info("Websocket open");var e = this._buildStream();this._conn.xmlOutput(e.tree());var n = t.serialize(e);this._conn.rawOutput(n), this.socket.send(n);
      }, _reqToData: function _reqToData(t) {
        return t;
      }, _send: function _send() {
        this._conn.flush();
      }, _sendRestart: function _sendRestart() {
        clearTimeout(this._conn._idleTimeout), this._conn._onIdle.bind(this._conn)();
      } }, t;
  }), function (t) {
    "function" == typeof n && n.amd && n("strophe", ["strophe-core", "strophe-bosh", "strophe-websocket"], function (t) {
      return t;
    });
  }(), e(["strophe-polyfill"]), e("strophe");
});

/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by aragornzhao on 2018/05/14
 * 功能： 会议管理 - 会议控制
 */

var Constants = __webpack_require__(2);
var Logger = __webpack_require__(3);
var XmppService = __webpack_require__(4);
var WebRtcService = __webpack_require__(7);
// let UserInfo = require("./user_info");

if (typeof console.assert === "undefined") {
    console.assert = function (val, msg) {
        // do nothing to pass
    };
}

var MeetingUserController = function () {
    function MeetingUserController() {
        var _this = this;

        _classCallCheck(this, MeetingUserController);

        this._test_mode = false;
        this.logger = new Logger();
        this.eventListenersMap = new Map();
        this.xmpp_service = XmppService.getInstance();
        this.rtc_service = WebRtcService.getInstance();
        this.meeting_id = 0;
        this.selfid = null;
        this.app_id = ""; //set by we_meet_sdk
        this.nickname = 'unnamed';
        this.host_uid = 0;
        this.user_map = new Map();

        var bind_this = function bind_this(funcname) {
            return _this[funcname] = _this[funcname].bind(_this);
        };
        bind_this('setSelfUserId');
        bind_this('getSelfId');
        bind_this('getUserById');
        bind_this('getSelfInfo');
        bind_this('formKeyById');
        bind_this('getUserIdList');
        bind_this('getUserInfoList');
        bind_this('setSelfNickname');
        bind_this('isInMeeting');
        bind_this('setMeetingId');
        bind_this('reset');
        bind_this('isHost');
        bind_this('handsUp');
        bind_this('kickout');
        bind_this('onLogout');
        bind_this('turnAudio');
        bind_this('turnVideo');
        bind_this('changeHost');
        bind_this('muteAudio');
        bind_this('muteVideo');
        bind_this('muteAllAudio');
        bind_this('muteAllVideo');
        bind_this('leaveMeeting');
        bind_this('updateUserInfo');
        bind_this('onChangeHostPush');
        bind_this('onKickoutCallBack');
        bind_this('onUserJoinCallBack');
        bind_this('onUserLeaveCallBack');
        bind_this('onKickedOutCallBack');
        bind_this('handleHandsUpRequest');
        bind_this('onUserUpdateCallBack');
        bind_this('registerEventHandler');
        bind_this('onUserKickedCallBack');
        bind_this('onNotifyHandsUpResult');
        bind_this('onLeaveMeetingCallBack');
        bind_this('onUpMediaStreamCallBack');
        bind_this('onHandsUpCompleteCallBack');
        bind_this('onMuteAudioCompleteCallBack');
        bind_this('onChangeHostCompleteCallBack');
        bind_this('onMuteVideoCompleteCallBack');
        bind_this('onNotifyHandsupPushCallBack');
        bind_this('onMuteAllAudioCompleteCallBack');
        bind_this('onMuteAllVideoCompleteCallBack');
        bind_this('onHandleHandsUpCallBack');
        bind_this('onUpdateUserInfoCallBack');
        bind_this('onModifyUserInfoCallBack');
        bind_this('onSwitchMediaPermissionPushCallBack');

        this.listenEvent();
    }

    _createClass(MeetingUserController, [{
        key: "setSelfUserId",
        value: function setSelfUserId(uid) {
            this.selfid = { uid: uid, app_id: this.app_id, instance_id: Constants.INSTANCE_ID.toString() };
        }
    }, {
        key: "getSelfId",
        value: function getSelfId() {
            return this.selfid;
        }
    }, {
        key: "getSelfUserId",
        value: function getSelfUserId() {
            return getSelfId();
        }
    }, {
        key: "setMeetingId",
        value: function setMeetingId(meetingId) {
            this.meeting_id = meetingId;
        }

        // the recommended way to get self nickname is to get self info
        // this method is NOT recommended, as it only reflects the nickname
        // when you join meeting.

    }, {
        key: "setSelfNickname",
        value: function setSelfNickname(nn) {
            this.nickname = nn;
        }
    }, {
        key: "isHost",
        value: function isHost() {
            var selfInfo = this.getSelfInfo();
            if (!selfInfo) {
                this.logger.error('MeetingUserController.isHost got self info for null!');
                return false;
            }
            return parseInt(selfInfo.is_host) === 1;
        }
    }, {
        key: "reset",
        value: function reset() {
            this.meeting_id = 0;
            this.selfid = null;
            this.user_map = new Map();
        }
    }, {
        key: "isInMeeting",
        value: function isInMeeting() {
            return this.meeting_id > 0;
        }
    }, {
        key: "getUserInfoList",
        value: function getUserInfoList() {
            var userInfoList = [];
            var _iteratorNormalCompletion = true;
            var _didIteratorError = false;
            var _iteratorError = undefined;

            try {
                for (var _iterator = this.user_map.values()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                    var value = _step.value;

                    userInfoList.push(value);
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion && _iterator.return) {
                        _iterator.return();
                    }
                } finally {
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }

            return userInfoList;
        }
    }, {
        key: "getUserIdList",
        value: function getUserIdList() {
            var _iteratorNormalCompletion2 = true;
            var _didIteratorError2 = false;
            var _iteratorError2 = undefined;

            try {
                for (var _iterator2 = this.user_map.values()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                    var value = _step2.value;

                    userIdList.push(value.id);
                }
            } catch (err) {
                _didIteratorError2 = true;
                _iteratorError2 = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion2 && _iterator2.return) {
                        _iterator2.return();
                    }
                } finally {
                    if (_didIteratorError2) {
                        throw _iteratorError2;
                    }
                }
            }

            return userIdList;
        }
    }, {
        key: "formKeyById",
        value: function formKeyById(id) {
            return this.getRoomUserId(id);
        }
    }, {
        key: "getRoomUserId",
        value: function getRoomUserId(userId) {
            return [userId.instance_id, userId.uid, userId.app_id].join('_');
        }
    }, {
        key: "getUserById",
        value: function getUserById(userId) {
            var key = this.formKeyById(userId);
            var userInfo = null;
            if (this.user_map.has(key)) {
                userInfo = this.user_map.get(key);
            }
            return userInfo;
        }
    }, {
        key: "getSelfInfo",
        value: function getSelfInfo() {
            var selfid = this.getSelfId();
            if (selfid) {
                var self = this.getUserById(selfid);
                return self;
            }
            return null;
        }

        /**
         * 事件监听
         */

    }, {
        key: "listenEvent",
        value: function listenEvent() {
            this.xmpp_service.registerEventHandler('user_join', this.onUserJoinCallBack);
            this.xmpp_service.registerEventHandler('user_leave', this.onUserLeaveCallBack);
            this.xmpp_service.registerEventHandler('user_update', this.onUserUpdateCallBack);
            this.xmpp_service.registerEventHandler('user_kicked', this.onUserKickedCallBack);

            var ret = this.xmpp_service.registerEventHandler('hands_up', this.onHandsUpCompleteCallBack);
            ret = this.xmpp_service.registerEventHandler('notify_hands_up_result', this.onNotifyHandsUpResult);

            ret = this.xmpp_service.registerEventHandler('mute_audio', this.onMuteAudioCompleteCallBack);
            ret = this.xmpp_service.registerEventHandler('mute_all_audio', this.onMuteAllAudioCompleteCallBack);
            ret = this.xmpp_service.registerEventHandler('mute_video', this.onMuteVideoCompleteCallBack);
            ret = this.xmpp_service.registerEventHandler('mute_all_video', this.onMuteAllVideoCompleteCallBack);
            ret = this.xmpp_service.registerEventHandler('handle_hands_up', this.onHandleHandsUpCallBack);
            ret = this.xmpp_service.registerEventHandler('user_status', this.onUpdateUserInfoCallBack);
            ret = this.xmpp_service.registerEventHandler("change_host", this.onChangeHostCompleteCallBack);
            ret = this.xmpp_service.registerEventHandler("leave_meeting", this.onLeaveMeetingCallBack);
            ret = this.xmpp_service.registerEventHandler("switch_media_permission_push", this.onSwitchMediaPermissionPushCallBack);
            ret = this.xmpp_service.registerEventHandler("notify_hands_up_push", this.onNotifyHandsupPushCallBack);
            ret = this.xmpp_service.registerEventHandler("up_media_stream", this.onUpMediaStreamCallBack);
            ret = this.xmpp_service.registerEventHandler("change_host_push", this.onChangeHostPush);
            ret = this.xmpp_service.registerEventHandler('modify_user_info', this.onModifyUserInfoCallBack);
            ret = this.xmpp_service.registerEventHandler('kickout', this.onKickoutCallBack);
            ret = this.xmpp_service.registerEventHandler('kicked_out', this.onKickedOutCallBack);
            ret = this.xmpp_service.registerEventHandler("logout", this.onLogout);
        }

        /**
         * Note: can ONLY be called internally!!
         * @param {object} user_info
         * e.g. {video_on: false, reason: 2}
         * e.g. {nickname: 'helloworld'}
         * @param {int} switch_type
         * select from Constants.UserState
         */

    }, {
        key: "updateUserInfo",
        value: function updateUserInfo(user_info, switch_type) {
            var userInfo = {
                meeting_id: this.meeting_id,
                type: switch_type
            };

            if (user_info.hasOwnProperty('video_on')) {
                userInfo.video_on = user_info.video_on;
            } else {
                var selfInfo = this.getSelfInfo();
                if (selfInfo === null) {
                    this.logger.error('MeetingUserController.updateUserInfo: failed to getSelfInfo()!');
                    return;
                }
                userInfo.video_on = selfInfo.video_on;
            }

            if (user_info.hasOwnProperty('video_reason')) {
                userInfo.video_reason = user_info.video_reason;
            } else {
                var _selfInfo = this.getSelfInfo();
                if (_selfInfo === null) {
                    this.logger.error('MeetingUserController.updateUserInfo: failed to getSelfInfo()!');
                    return;
                }
                userInfo.video_reason = _selfInfo.video_reason;
            }

            if (user_info.hasOwnProperty('audio_on')) {
                userInfo.audio_on = user_info.audio_on;
            } else {
                var _selfInfo2 = this.getSelfInfo();
                if (_selfInfo2 === null) {
                    this.logger.error('MeetingUserController.updateUserInfo: failed to getSelfInfo()!');
                    return;
                }
                userInfo.audio_on = _selfInfo2.audio_on;
            }

            if (user_info.hasOwnProperty('audio_reason')) {
                userInfo.audio_reason = user_info.audio_reason;
            } else {
                var _selfInfo3 = this.getSelfInfo();
                if (_selfInfo3 === null) {
                    this.logger.error('MeetingUserController.updateUserInfo: failed to getSelfInfo()!');
                    return;
                }
                userInfo.audio_reason = _selfInfo3.audio_reason;
            }

            if (user_info.hasOwnProperty('share_on')) {
                userInfo.share_on = user_info.share_on;
            } else {
                userInfo.share_on = 0;
            }

            if (user_info.hasOwnProperty('share_reason')) {
                userInfo.share_reason = user_info.share_reason;
            } else {
                var _selfInfo4 = this.getSelfInfo();
                if (_selfInfo4 === null) {
                    this.logger.error('MeetingUserController.updateUserInfo: failed to getSelfInfo()!');
                    return;
                }
                userInfo.share_reason = _selfInfo4.share_reason;
            }

            if (user_info.hasOwnProperty('nickname')) {
                userInfo.nickname = user_info.nickname;
            } else {
                var _selfInfo5 = this.getSelfInfo();
                if (_selfInfo5 === null) {
                    this.logger.error('MeetingUserController.updateUserInfo: failed to getSelfInfo()!');
                    return;
                }
                userInfo.nickname = _selfInfo5.nickname;
            }

            this.xmpp_service.userStatusRequest(userInfo);
        }
    }, {
        key: "handsUp",
        value: function handsUp(isUp, permissionList) {
            if (!this.isInMeeting()) {
                this.logger.error("handsUp failed: not in meeting");
                return false;
            }

            this.xmpp_service.handsUpRequest(this.meeting_id, isUp ? 1 : 0, permissionList);
            return true;
        }
    }, {
        key: "turnAudio",
        value: function turnAudio(on) {
            if (on) {
                this.xmpp_service.upMediaStreamRequest(this.meeting_id, Constants.MediaType.AUDIO);
            } else {
                this.updateUserInfo({
                    audio_on: 0,
                    audio_reason: Constants.SwitchReason.BYSELF
                }, Constants.UserState.UPDATE);
                var cb = this.getEventHandler('turn_audio');
                cb(true, { status: "off" });
            }
        }
    }, {
        key: "turnVideo",
        value: function turnVideo(on) {
            if (on) {
                this.xmpp_service.upMediaStreamRequest(this.meeting_id, Constants.MediaType.VIDEO);
            } else {
                this.updateUserInfo({
                    video_on: 0,
                    video_reason: Constants.SwitchReason.BYSELF
                }, Constants.UserState.UPDATE);
                var cb = this.getEventHandler('turn_video');
                cb(true, { status: "off" });
            }
        }

        /**
         * 离开会议
         */

    }, {
        key: "leaveMeeting",
        value: function leaveMeeting() {
            this.xmpp_service.leaveMeetingRequest(this.meeting_id);
            return true;
        }

        /**
         * @param {object} account 需要包含uid, app_id, instance_id
         * @param {int} req_type 1,2,3
         * @param {int} is_grant 0 or 1
         */

    }, {
        key: "handleHandsUpRequest",
        value: function handleHandsUpRequest(account, req_type, is_grant) {
            return this.xmpp_service.handleHandsUpRequest(this.meeting_id, account, req_type, is_grant);
        }
    }, {
        key: "changeHost",
        value: function changeHost(account) {
            if (!this.isInMeeting()) {
                this.logger.error("MUC.changeHost: not in meeting");
                return false;
            }

            if (!this.isHost()) {
                this.logger.error("only host can do changeHost");
                return false;
            }

            this.xmpp_service.changeHostRequest(this.meeting_id, account);
            return true;
        }
    }, {
        key: "spotlightVideo",
        value: function spotlightVideo(account) {
            if (this._test_mode === false && !this.isInMeeting()) {
                this.logger.error("not in meeting");
                return false;
            }

            if (!this.isHost()) {
                this.logger.error("only host can do spotlightVideo");
                return false;
            }

            // todo
            this.xmpp_service.setVideoLayoutRequest();
            return true;
        }
    }, {
        key: "muteAudio",
        value: function muteAudio(account, is_mute) {
            if (this._test_mode === false && !this.isInMeeting()) {
                this.logger.error("not in meeting");
                return false;
            }

            if (!this.isHost()) {
                this.logger.error("only host can do this operation");
                return false;
            }

            this.xmpp_service.switchMediaPermissionRequest(account, this.meeting_id, Constants.MediaType.AUDIO, is_mute ? 0 : 1, 0);
            return true;
        }
    }, {
        key: "muteAllAudio",
        value: function muteAllAudio(is_mute) {
            if (this._test_mode === false && !this.isInMeeting()) {
                this.logger.error("not in meeting");
                return false;
            }

            if (!this.isHost()) {
                this.logger.error("only host can do this operation");
                return false;
            }

            var selfInfo = this.getSelfInfo();
            this.xmpp_service.switchMediaPermissionRequest(selfInfo.id, this.meeting_id, Constants.MediaType.AUDIO, is_mute ? 0 : 1, 1);
            return true;
        }
    }, {
        key: "muteVideo",
        value: function muteVideo(account, is_mute) {
            if (this._test_mode === false && !this.isInMeeting()) {
                this.logger.error("not in meeting");
                return false;
            }

            if (!this.isHost()) {
                this.logger.error("only host can do this operation");
                return false;
            }

            this.xmpp_service.switchMediaPermissionRequest(account, this.meeting_id, Constants.MediaType.VIDEO, is_mute ? 0 : 1, 0);
            return true;
        }
    }, {
        key: "muteAllVideo",
        value: function muteAllVideo(is_mute) {
            if (this._test_mode === false && !this.isInMeeting()) {
                this.logger.error("not in meeting");
                return false;
            }

            if (!this.isHost()) {
                this.logger.error("only host can do this operation");
                return false;
            }

            this.xmpp_service.switchMediaPermissionRequest(this.getSelfInfo().id, this.meeting_id, Constants.MediaType.VIDEO, is_mute ? 0 : 1, 1);
            return true;
        }
    }, {
        key: "modifyNickname",
        value: function modifyNickname(user_id, nickname) {
            this.xmpp_service.modifyNicknameRequest(this.meeting_id, user_id, nickname);
        }
    }, {
        key: "kickout",
        value: function kickout(user_id) {
            this.xmpp_service.kickoutRequest(this.meeting_id, [user_id], 1);
        }
    }, {
        key: "onUserJoinCallBack",
        value: function onUserJoinCallBack(flag, data) {
            if (data) {
                this.logger.log('meeting user controller: user_join, data:', JSON.stringify(data));
            }
            var cb = this.getEventHandler('user_join');
            if (!flag) {
                cb(flag, data);
                return;
            }

            for (var i = 0; i < data.user_list.length; i++) {
                var user = data.user_list[i];
                var key = this.formKeyById(user.id);
                this.user_map.set(key, user);
            }

            cb(flag, data);
        }
    }, {
        key: "onUserLeaveCallBack",
        value: function onUserLeaveCallBack(flag, data) {
            if (data) {
                console.log('user leave data:', JSON.stringify(data));
            }
            this.logger.debug('MUC onUserLeaveCallBack!!');
            var cb = this.getEventHandler('user_leave');
            if (!flag) {
                cb(flag, data);
                return;
            }

            for (var i = 0; i < data.user_list.length; i++) {
                var user = data.user_list[i];
                var key = this.formKeyById(user.id);
                this.user_map.delete(key);
            }

            cb(flag, data);
        }
    }, {
        key: "onUserUpdateCallBack",
        value: function onUserUpdateCallBack(flag, data) {
            if (data) {
                console.log('user update data:', JSON.stringify(data));
            }
            var cb = this.getEventHandler('user_update');
            if (!flag) {
                cb(flag, data);
                return;
            }

            var updateUser = function updateUser(oldData, newData) {
                var propList = ['audio_on', 'audio_reason', 'handsup', 'is_creator', 'is_host', 'nickname', 'share_on', 'share_reason', 'user_type', 'video_on', 'video_reason'];

                var _iteratorNormalCompletion3 = true;
                var _didIteratorError3 = false;
                var _iteratorError3 = undefined;

                try {
                    for (var _iterator3 = propList[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
                        var prop = _step3.value;

                        if (newData[prop] !== "") {
                            oldData[prop] = newData[prop];
                        }
                    }
                } catch (err) {
                    _didIteratorError3 = true;
                    _iteratorError3 = err;
                } finally {
                    try {
                        if (!_iteratorNormalCompletion3 && _iterator3.return) {
                            _iterator3.return();
                        }
                    } finally {
                        if (_didIteratorError3) {
                            throw _iteratorError3;
                        }
                    }
                }

                if (newData.id.av_uid !== "") {
                    oldData.id.av_uid = newData.id.av_uid;
                }
            };

            for (var i = 0; i < data.user_list.length; i++) {
                var user = data.user_list[i];
                var key = this.formKeyById(user.id);
                var currUser = this.user_map.get(key);
                updateUser(currUser, user);
                this.user_map.set(key, currUser);
            }

            cb(flag, data);
        }
    }, {
        key: "onUserKickedCallBack",
        value: function onUserKickedCallBack(flag, data) {
            if (data) {
                console.log('user kicked data:', JSON.stringify(data));
            }
            var cb = this.getEventHandler('user_kicked');
            if (!flag) {
                cb(flag, data);
                return;
            }

            for (var i = 0; i < data.user_list.length; i++) {
                var user = data.user_list[i];
                var key = this.formKeyById(user.id);
                this.user_map.delete(key);
            }

            cb(flag, data);
        }
    }, {
        key: "onChangeHostPush",
        value: function onChangeHostPush(flag, data) {
            var cb = this.getEventHandler('change_host_push');
            if (!flag) {
                cb(flag, data);
                return;
            }

            this.logger.debug('MUC.onChangeHostPush data:', data);

            var user = this.getUserById(data.host);
            if (!user) {
                this.logger.error('MUC.onChangeHostPush failed to get host user!');
                return;
            }

            var _iteratorNormalCompletion4 = true;
            var _didIteratorError4 = false;
            var _iteratorError4 = undefined;

            try {
                for (var _iterator4 = this.user_map.values()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
                    var u = _step4.value;

                    u.is_host = "0";
                }
            } catch (err) {
                _didIteratorError4 = true;
                _iteratorError4 = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion4 && _iterator4.return) {
                        _iterator4.return();
                    }
                } finally {
                    if (_didIteratorError4) {
                        throw _iteratorError4;
                    }
                }
            }

            user.is_host = "1";

            cb(flag, data);
        }
    }, {
        key: "onSpotLightVideoChangedCallBack",
        value: function onSpotLightVideoChangedCallBack(flag, data) {
            var cb = this.getEventHandler('spot_light_video_changed');
            cb(flag, data);
        }
    }, {
        key: "onHandsUpCompleteCallBack",
        value: function onHandsUpCompleteCallBack(flag, data) {
            var cb = this.getEventHandler('hands_up_complete');
            cb(flag, data);
        }
    }, {
        key: "onNotifyHandsUpResult",
        value: function onNotifyHandsUpResult(flag, data) {
            var cb = this.getEventHandler('notify_hands_up_result');
            cb(flag, data);
        }
    }, {
        key: "onChangeHostCompleteCallBack",
        value: function onChangeHostCompleteCallBack(flag, data) {
            var cb = this.getEventHandler('change_host');
            cb(flag, data);
        }
    }, {
        key: "onRemoveUserCompleteCallBack",
        value: function onRemoveUserCompleteCallBack(flag, data) {
            //
        }
    }, {
        key: "onSpotlightVideoCompleteCallBack",
        value: function onSpotlightVideoCompleteCallBack(flag, data) {
            var cb = this.getEventHandler('spot_light_video_changed');
            cb(flag, data);
        }
    }, {
        key: "onMuteAudioCompleteCallBack",
        value: function onMuteAudioCompleteCallBack(flag, data) {
            var cb = this.getEventHandler('mute_audio_complete');
            cb(flag, data);
        }
    }, {
        key: "onMuteAllAudioCompleteCallBack",
        value: function onMuteAllAudioCompleteCallBack(flag, data) {
            var cb = this.getEventHandler('mute_all_audio_complete');
            cb(flag, data);
        }
    }, {
        key: "onHandleHandsUpCallBack",
        value: function onHandleHandsUpCallBack(flag, data) {
            var cb = this.getEventHandler('handle_hands_up');
            cb(flag, data);
        }
    }, {
        key: "onMuteVideoCompleteCallBack",
        value: function onMuteVideoCompleteCallBack(flag, data) {
            var cb = this.getEventHandler('mute_video_complete');
            cb(flag, data);
        }
    }, {
        key: "onMuteAllVideoCompleteCallBack",
        value: function onMuteAllVideoCompleteCallBack(flag, data) {
            var cb = this.getEventHandler('mute_all_video_complete');
            cb(flag, data);
        }
    }, {
        key: "onUpdateUserInfoCallBack",
        value: function onUpdateUserInfoCallBack(flag, data) {
            var cb = this.getEventHandler('user_status');
            cb(flag, data);
        }
    }, {
        key: "onModifyUserInfoCallBack",
        value: function onModifyUserInfoCallBack(flag, data) {
            var cb = this.getEventHandler('modify_user_info');
            cb(flag, data);
        }
    }, {
        key: "onLeaveMeetingCallBack",
        value: function onLeaveMeetingCallBack(flag, data) {
            var cb = this.getEventHandler('leave_meeting');
            if (!flag) {
                cb(flag, data);
                return;
            }

            cb(flag, data);
            if (Constants.INSTANCE_ID === Constants.InstanceType.INSTANCE_WEB) {
                this.rtc_service.leaveRoom();
            }
            this.reset();
        }
    }, {
        key: "onKickoutCallBack",
        value: function onKickoutCallBack(flag, data) {
            var cb = this.getEventHandler('kickout');
            cb(flag, data);
        }
    }, {
        key: "onKickedOutCallBack",
        value: function onKickedOutCallBack(flag, data) {
            // do callback first, as the client should exit video/audio room first
            var cb = this.getEventHandler('kicked_out');
            cb(flag, data);
            if (Constants.INSTANCE_ID === Constants.InstanceType.INSTANCE_WEB) {
                this.rtc_service.leaveRoom();
            }
            // then update status to server
            this.xmpp_service.finishKickedOutRequest(this.meeting_id);
            // then clear self
            this.reset();
        }
    }, {
        key: "onSwitchMediaPermissionPushCallBack",
        value: function onSwitchMediaPermissionPushCallBack(flag, data) {
            var stype = parseInt(data.op_type);
            if (stype === Constants.MediaType.AUDIO) {
                this.updateUserInfo({
                    audio_on: parseInt(data.is_grant),
                    audio_reason: Constants.SwitchReason.BYHOST
                }, Constants.UserState.UPDATE);
            } else if (stype === Constants.MediaType.VIDEO) {
                this.updateUserInfo({
                    video_on: parseInt(data.is_grant),
                    video_reason: Constants.SwitchReason.BYHOST
                }, Constants.UserState.UPDATE);
            } else if (stype === Constants.MediaType.SCREEN_SHARE) {
                this.updateUserInfo({
                    share_on: parseInt(data.is_grant),
                    share_reason: Constants.SwitchReason.BYHOST
                }, Constants.UserState.UPDATE);
            }
            var cb = this.getEventHandler('switch_media_permission_push');
            cb(flag, data);
        }
    }, {
        key: "onNotifyHandsupPushCallBack",
        value: function onNotifyHandsupPushCallBack(flag, data) {
            var cb = this.getEventHandler('notify_hands_up_push');
            cb(flag, data);
        }
    }, {
        key: "onUpMediaStreamCallBack",
        value: function onUpMediaStreamCallBack(flag, data) {
            this.logger.debug('MUC onUpMediaStreamCallBack flag:', flag, 'data:', JSON.stringify(data));
            if (data.meeting_id != this.meeting_id) {
                this.logger.error('MUC onUpMediaStreamCallBack DIFFERENT meeting_id! data.meeting_id:', data.meeting_id, 'self.meeting_id:', this.meeting_id);
                return;
            }
            var updateInfo = {};
            var _iteratorNormalCompletion5 = true;
            var _didIteratorError5 = false;
            var _iteratorError5 = undefined;

            try {
                for (var _iterator5 = data.permission_list[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
                    var pinfo = _step5.value;

                    if (pinfo['type'] === Constants.MediaType.AUDIO) {
                        updateInfo.audio_on = pinfo['is_grant'];
                        updateInfo.audio_reason = Constants.SwitchReason.BYSELF;
                        var cb = this.getEventHandler('turn_audio');
                        if (pinfo['is_grant']) {
                            cb(true, { status: "on" });
                        } else {
                            cb(false, { status: "off" });
                        }
                    } else if (pinfo['type'] === Constants.MediaType.VIDEO) {
                        updateInfo.video_on = pinfo['is_grant'];
                        updateInfo.video_reason = Constants.SwitchReason.BYSELF;
                        var _cb = this.getEventHandler('turn_video');
                        if (pinfo['is_grant']) {
                            _cb(true, { status: "on" });
                        } else {
                            _cb(false, { status: "off" });
                        }
                    }
                }
            } catch (err) {
                _didIteratorError5 = true;
                _iteratorError5 = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion5 && _iterator5.return) {
                        _iterator5.return();
                    }
                } finally {
                    if (_didIteratorError5) {
                        throw _iteratorError5;
                    }
                }
            }

            this.updateUserInfo(updateInfo, Constants.UserState.UPDATE);
        }
    }, {
        key: "onLogout",
        value: function onLogout(flag, data) {
            console.log('meeting_user_controller logout');
            if (Constants.INSTANCE_ID === Constants.InstanceType.INSTANCE_WEB) {
                this.rtc_service.leaveRoom();
            }
            this.reset();
        }

        /**
         * 注释事件回调
         * @param event_key： 事件名称
         * @param callBackFun： 回调函数
         * @returns {boolean}
         */

    }, {
        key: "registerEventHandler",
        value: function registerEventHandler(event_key, callBackFun) {
            var event_list = ['user_status', 'user_join', 'user_leave', 'user_update', 'user_kicked', 'spot_light_video_changed', 'hands_up_complete', 'handle_hands_up', 'change_host_complete', 'remove_user_complete', 'spot_light_video_complete', 'mute_audio_complete', 'mute_video_complete', 'mute_all_audio_complete', 'mute_all_video_complete', 'modify_nickname', 'leave_meeting', 'switch_media_permission_push', 'notify_hands_up_push', 'change_host', 'turn_audio', 'turn_video', 'modify_user_info', 'change_host_push', 'kickout', 'kicked_out', 'notify_hands_up_result'];

            if (event_list.indexOf(event_key) === -1) {
                console.error('MUC.registerEventHandler: adding an unrecognized event:', event_key);
                return false;
            }

            if (typeof callBackFun === "function") {
                var arrcb = this.eventListenersMap.get(event_key);
                if (arrcb === undefined) {
                    arrcb = [];
                }
                arrcb.push(callBackFun);
                this.logger.debug("MUC.registerEventHandler", event_key, arrcb.length);
                this.eventListenersMap.set(event_key, arrcb);
                return true;
            }

            return false;
        }
    }, {
        key: "removeEventHandler",
        value: function removeEventHandler(event_key, callBackFun) {
            if (typeof callBackFun === "function") {
                var arrcb = this.eventListenersMap.get(event_key);
                if (arrcb === undefined) {
                    this.logger.debug("MUC.removeEventHandler arrcb not found.");
                    return false;
                }
                var index = arrcb.indexOf(callBackFun);
                if (index > -1) {
                    arrcb.splice(index, 1);
                } else {
                    this.logger.debug("MUC.registerEventHandler func not found.");
                }
                this.logger.debug("MUC.registerEventHandler", event_key, arrcb.length);
                this.eventListenersMap.set(event_key, arrcb);
                return true;
            }
        }

        /**
         * 获取事件回调函数
         * @param event_key: 事件名称
         * @returns {function} 回调函数
         */

    }, {
        key: "getEventHandler",
        value: function getEventHandler(event_key) {
            var arrcb = this.eventListenersMap.get(event_key);
            if (arrcb === undefined) {
                return function () {};
            }

            // const caller; // can we use const here?
            var caller = function caller(flag, data) {
                var _iteratorNormalCompletion6 = true;
                var _didIteratorError6 = false;
                var _iteratorError6 = undefined;

                try {
                    for (var _iterator6 = arrcb[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
                        var cb = _step6.value;

                        cb(flag, data);
                    }
                } catch (err) {
                    _didIteratorError6 = true;
                    _iteratorError6 = err;
                } finally {
                    try {
                        if (!_iteratorNormalCompletion6 && _iterator6.return) {
                            _iterator6.return();
                        }
                    } finally {
                        if (_didIteratorError6) {
                            throw _iteratorError6;
                        }
                    }
                }
            };

            return caller;
        }
    }], [{
        key: "getInstance",
        value: function getInstance() {
            if (MeetingUserController.prototype.instance === undefined) {
                MeetingUserController.prototype.instance = new MeetingUserController();
            }
            return MeetingUserController.prototype.instance;
        }
    }]);

    return MeetingUserController;
}();

module.exports = MeetingUserController;

/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by aragornzhao on 2018/05/24
 * 功能： webRtc能力封装
 */

var Constants = __webpack_require__(2);
var Logger = __webpack_require__(3);

var WebRtcService = function () {
    function WebRtcService() {
        _classCallCheck(this, WebRtcService);

        this.logger = new Logger();
        this.RTC = null;
        this.eventListenersMap = new Map();
        this.savedAudioOn = true;
        this.savedVideoOn = true;
    }

    _createClass(WebRtcService, [{
        key: "canSupportRTC",
        value: function canSupportRTC() {
            var detector = WebRTCAPI.fn.detectRTC();
            return detector.support;
        }

        /**
         * 初始化webRTC
         * @param init_param: 出售化参数
         * @returns {boolean} 是否正常完成初始化
         */

    }, {
        key: "initWebRtc",
        value: function initWebRtc(init_param) {
            var _this = this;

            if (init_param === undefined) {
                this.logger.error('there is no init para info');
                return false;
            }

            this.savedAudioOn = init_param.is_enable_audio;
            this.savedVideoOn = init_param.is_enable_video;

            this.RTC = new WebRTCAPI({
                "useCloud": 0, // !!important 必须显式地置为0才可以走自研环境
                "userId": init_param.user_id,
                "sdkAppId": init_param.sdk_appid,
                "accountType": init_param.account_type,
                "userSig": init_param.user_sig,
                "audio": true,
                "video": true,
                "closeLocalMedia": false
            }, function (success_data) {
                _this.logger.info('init WebRTC success');
                var cb = _this.getEventHandler('init');
                cb(true, success_data);
            }, function (fail_data) {
                _this.logger.info('init WebRTC failed');
                var cb = _this.getEventHandler('init');
                cb(false, fail_data);
            });
        }

        /**
         * 创建音视频房间
         * @param room_param ： 房间参数
         *      room_id | 音视频房间号
         *      private_key | 腾讯云私钥
         *      role | 用户角色
         * @returns {boolean} ：是否正常创建
         */

    }, {
        key: "createRoom",
        value: function createRoom(room_param) {
            var _this2 = this;

            if (!this.RTC) {
                return false;
            }

            if (room_param === undefined) {
                this.logger.error('there is no room para info');
                return false;
            }

            console.log('webrtc_service calling this.RTC.createRoom, with room_param:', room_param);

            this.RTC.createRoom({
                roomid: room_param.room_id * 1,
                privateMapKey: room_param.private_key,
                role: room_param.role
                // pstnBizType: 1000
            }, function () {
                _this2.listenRTCEvent();
                var cb = _this2.getEventHandler('create_room');
                cb(true);
                _this2.logger.info("enter room success");
            }, function (fail_data) {
                var cb = _this2.getEventHandler('create_room');
                cb(false, fail_data);
                _this2.logger.info("enter room failed");
            });
            return true;
        }

        /**
         * 退房
         * @returns {boolean}
         */

    }, {
        key: "leaveRoom",
        value: function leaveRoom() {
            var _this3 = this;

            if (!this.RTC) {
                return false;
            }

            this.stopRTC();

            this.RTC.quit(function () {
                var cb = _this3.getEventHandler('leave_room');
                cb(true, { msg: "leave room success" });
                _this3.logger.info("leave room success");
            }, function () {
                var cb = _this3.getEventHandler('leave_room');
                cb(false, { msg: "leave room fail" });
                _this3.logger.info("leave room fail");
            });

            return true;
        }

        /**
         * 注册回调函数响应
         * @param event_key  事件名称
         * @param callBackFun 回调函数对象
         * @returns {boolean}
         */

    }, {
        key: "registerEventHandler",
        value: function registerEventHandler(event_key, callBackFun) {
            if (typeof callBackFun === "function") {
                this.eventListenersMap.set(event_key, callBackFun);
                return true;
            }

            return false;
        }

        /**
         * 获取回调函数
         * @param event_key
         * @returns {function}
         */

    }, {
        key: "getEventHandler",
        value: function getEventHandler(event_key) {
            var cb = this.eventListenersMap.get(event_key);
            if (cb === undefined) {
                cb = function cb() {};
            }
            return cb;
        }

        /**
         * 事件注册
         */

    }, {
        key: "listenRTCEvent",
        value: function listenRTCEvent() {
            var _this4 = this;

            this.RTC.on('onLocalStreamAdd', function (data) {
                if (!_this4.savedAudioOn) {
                    _this4.closeAudio();
                }
                if (!_this4.savedVideoOn) {
                    _this4.closeVideo();
                }
                var cb = _this4.getEventHandler('local_stream_add');
                cb(data);
            });

            this.RTC.on('onRemoteStreamUpdate', function (data) {
                var cb = _this4.getEventHandler('remote_stream_update');
                cb(data);
            });

            this.RTC.on('onRemoteStreamRemove', function (data) {
                var cb = _this4.getEventHandler('remote_stream_remove');
                cb(data);
            });

            this.RTC.on('onWebSocketClose', function (data) {
                var cb = _this4.getEventHandler('web_socket_close');
                cb(data);
            });

            this.RTC.on('onRelayTimeout', function (data) {
                var cb = _this4.getEventHandler('relay_time_out');
                cb(data);
            });

            this.RTC.on('onKickout', function (data) {
                var cb = _this4.getEventHandler('kick_out');
                cb(data);
            });
        }

        /**
         * 主动发起推流，拉流
         */

    }, {
        key: "startRTC",
        value: function startRTC() {
            if (this.RTC) {
                this.RTC.startRTC();
            }
        }

        /**
         * 主动停止推流
         */

    }, {
        key: "stopRTC",
        value: function stopRTC() {
            if (this.RTC) {
                this.RTC.stopRTC();
            }
        }

        /**
         * 获取本地音视频流
         * @returns {*}
         */

    }, {
        key: "getLocalStream",
        value: function getLocalStream() {
            return this.RTC.getLocalStream();
        }

        /**
         * 不采集音频
         * @returns {boolean}
         */

    }, {
        key: "closeAudio",
        value: function closeAudio() {
            this.RTC.closeAudio();
            return true;
        }

        /**
         * 采集音频、取消静音
         * @returns {boolean}
         */

    }, {
        key: "openAudio",
        value: function openAudio() {
            this.RTC.openAudio();
            return true;
        }

        /**
         * 不采集视频
         * @returns {boolean}
         */

    }, {
        key: "closeVideo",
        value: function closeVideo() {
            this.RTC.closeVideo();
            return true;
        }

        /**
         * 打开视频采集
         * @returns {boolean}
         */

    }, {
        key: "openVideo",
        value: function openVideo() {
            this.RTC.openVideo();
            return true;
        }

        /**
         * 获取唐倩音视频采集配置
         * @returns {*}
         *      status.video |true | false (表示当前是否采集视频)
         *      status.audio |true | false (表示当前是否采集音频)
         */

    }, {
        key: "getLocalMediaStatus",
        value: function getLocalMediaStatus() {
            return this.RTC.getLocalMediaStatus();
        }

        /**
         * 切换画面设定的用户角色
         * @param role_name | 角色名称
         */

    }, {
        key: "changeSpearRole",
        value: function changeSpearRole(role_name) {
            this.RTC.changeSpearRole(role_name);
            return true;
        }

        /**
         * 枚举摄像头
         */

    }, {
        key: "getVideoDevices",
        value: function getVideoDevices() {
            this.RTC.getVideoDevices(function (devices) {
                var cb = this.getEventHandler('get_video_device');
                cb(devices);
            });
            return true;
        }

        /**
         * 选择摄像头
         * @param device
         */

    }, {
        key: "chooseVideoDevice",
        value: function chooseVideoDevice(device) {
            this.RTC.chooseVideoDevice(device);
            return true;
        }

        /**
         * 枚举麦克风
         */

    }, {
        key: "getAudioDevices",
        value: function getAudioDevices() {
            this.RTC.getAudioDevices(function (devices) {
                var cb = this.getEventHandler('get_audio_device');
                cb(devices);
            });

            return true;
        }

        /**
         * 选择麦克风
         * @param device
         * @returns {boolean}
         */

    }, {
        key: "chooseAudioDevice",
        value: function chooseAudioDevice(device) {
            this.RTC.chooseAudioDevice(device);
            return true;
        }
    }], [{
        key: "getInstance",


        /**
         * 返回单例
         * @returns {WebRtcService}
         */
        value: function getInstance() {
            if (WebRtcService.prototype.instance === undefined) {
                WebRtcService.prototype.instance = new WebRtcService();
            }
            return WebRtcService.prototype.instance;
        }
    }]);

    return WebRtcService;
}();

module.exports = WebRtcService;

/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by aragornzhao on 2018/05/14
 * 功能： 会议管理 - 音频控制
 */

var Constants = __webpack_require__(2);
var Logger = __webpack_require__(3);
var WebRtcService = __webpack_require__(7);
var XmppService = __webpack_require__(4);

var MeetingAudioController = function () {
  function MeetingAudioController() {
    var _this = this;

    _classCallCheck(this, MeetingAudioController);

    this.logger = new Logger();
    this.eventListenersMap = new Map();
    this.rtc_service = WebRtcService.getInstance();
    this.xmpp_service = XmppService.getInstance();

    this.onAudioComplete = this.onAudioComplete.bind(this);

    var bind_this = function bind_this(func_name) {
      return _this[func_name] = _this[func_name].bind(_this);
    };
    bind_this('enableAudio');

    this.listenEvent();
  }

  _createClass(MeetingAudioController, [{
    key: "enableAudio",


    /**
     * 本地开启/关闭声音
     * @param is_enable 开关
     */
    value: function enableAudio(is_enable) {
      // 向后台请求
      if (is_enable) {
        this.rtc_service.openAudio();
      } else {
        this.rtc_service.closeAudio();
      }

      return true;
    }
  }, {
    key: "onAudioComplete",
    value: function onAudioComplete(flag, data) {
      var cb = this.getEventHandler('audio_complete');
      cb(flag, data);
    }

    /**
     * 控制扬声器
     * @param user_id
     * @param is_enable
     */

  }, {
    key: "enableSpeaker",
    value: function enableSpeaker(user_id, is_enable) {}
    // WebRtc 没有控制扬声器能力


    /**
     * 事件监听
     */

  }, {
    key: "listenEvent",
    value: function listenEvent() {
      this.xmpp_service.registerEventHandler('audio_complete', this.onAudioComplete);
    }

    /**
     * 注释事件回调
     * @param event_key： 事件名称
     * @param callBackFun： 回调函数
     */

  }, {
    key: "registerEventHandler",
    value: function registerEventHandler(event_key, callBackFun) {
      var event_list = ['audio_complete'];
      if (event_list.indexOf(event_key) === -1) {
        return false;
      }

      if (typeof callBackFun === "function") {
        this.eventListenersMap.set(event_key, callBackFun);
        return true;
      }

      return false;
    }

    /**
     * 获取事件回调函数
     * @param event_key: 事件名称
     * @returns {function} 回调函数
     */

  }, {
    key: "getEventHandler",
    value: function getEventHandler(event_key) {
      var cb = this.eventListenersMap.get(event_key);
      if (cb === undefined) {
        cb = function cb(flag, data) {};
      }

      return cb;
    }
  }], [{
    key: "getInstance",
    value: function getInstance() {
      if (MeetingAudioController.prototype.instance === undefined) {
        MeetingAudioController.prototype.instance = new MeetingAudioController();
      }
      return MeetingAudioController.prototype.instance;
    }
  }]);

  return MeetingAudioController;
}();

module.exports = MeetingAudioController;

/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by aragornzhao on 2018/05/14
 * 功能： 会议管理 - 视频控制
 */

var Constants = __webpack_require__(2);
var Logger = __webpack_require__(3);
var WebRtcService = __webpack_require__(7);
var XmppService = __webpack_require__(4);

var MeetingVideoController = function () {
    function MeetingVideoController() {
        var _this = this;

        _classCallCheck(this, MeetingVideoController);

        this.logger = new Logger();
        this.xmpp_service = XmppService.getInstance();
        this.rtc_service = WebRtcService.getInstance();
        this.eventListenersMap = new Map();

        this.onVideoComplete = this.onVideoComplete.bind(this);
        this.onLocalStreamAdd = this.onLocalStreamAdd.bind(this);
        this.onRemoteStreamAdd = this.onRemoteStreamAdd.bind(this);
        this.onRemoteStreamRemove = this.onRemoteStreamRemove.bind(this);

        var bind_this = function bind_this(func_name) {
            return _this[func_name] = _this[func_name].bind(_this);
        };
        bind_this('enableVideo');

        this.listenEvent();
    }

    _createClass(MeetingVideoController, [{
        key: "enableVideo",


        /**
         * 请求看到某个会议成员的图像
         * @param is_enable
         */
        value: function enableVideo(is_enable) {
            // 向后台请求
            if (is_enable) {
                this.rtc_service.openVideo();
            } else {
                this.rtc_service.closeVideo();
            }
            return true;
        }
    }, {
        key: "start",
        value: function start() {
            this.rtc_service.startRTC();
        }
    }, {
        key: "stop",
        value: function stop() {
            this.rtc_service.stopRTC();
        }
    }, {
        key: "onVideoComplete",
        value: function onVideoComplete(flag, data) {
            var cb = this.getEventHandler('video_complete');
            cb(flag, data);
        }
    }, {
        key: "onLocalStreamAdd",
        value: function onLocalStreamAdd(info) {
            if (info.stream && info.stream.active === true) {
                var cb = this.getEventHandler('local_stream_add');
                cb(true, info);
            }
        }
    }, {
        key: "onRemoteStreamAdd",
        value: function onRemoteStreamAdd(info) {
            if (info.stream && info.stream.active === true) {
                var cb = this.getEventHandler('remote_stream_add');
                cb(true, info);
            }
        }
    }, {
        key: "onRemoteStreamRemove",
        value: function onRemoteStreamRemove(info) {
            var cb = this.getEventHandler('remote_stream_remove');
            cb(true, info);
        }

        /**
         * 事件监听
         */

    }, {
        key: "listenEvent",
        value: function listenEvent() {
            this.xmpp_service.registerEventHandler('video_complete', this.onAudioComplete);
            this.rtc_service.registerEventHandler('local_stream_add', this.onLocalStreamAdd);
            this.rtc_service.registerEventHandler('remote_stream_update', this.onRemoteStreamAdd);
            this.rtc_service.registerEventHandler('remote_stream_remove', this.onRemoteStreamRemove);
        }

        /**
         * 注释事件回调
         * @param event_key： 事件名称
         * @param callBackFun： 回调函数
         */

    }, {
        key: "registerEventHandler",
        value: function registerEventHandler(event_key, callBackFun) {
            var event_list = ['video_complete', 'local_stream_add', 'remote_stream_add', 'remote_stream_remove'];
            if (event_list.indexOf(event_key) === -1) {
                return false;
            }
            this.eventListenersMap.set(event_key, callBackFun);
            return true;
        }

        /**
         * 获取事件回调函数
         * @param event_key: 事件名称
         * @returns {function} 回调函数
         */

    }, {
        key: "getEventHandler",
        value: function getEventHandler(event_key) {
            var cb = this.eventListenersMap.get(event_key);
            if (cb === undefined) {
                cb = function cb() {};
            }

            return cb;
        }
    }], [{
        key: "getInstance",
        value: function getInstance() {
            if (MeetingVideoController.prototype.instance === undefined) {
                MeetingVideoController.prototype.instance = new MeetingVideoController();
            }
            return MeetingVideoController.prototype.instance;
        }
    }]);

    return MeetingVideoController;
}();

module.exports = MeetingVideoController;

/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by aragornzhao on 2018/05/14
 * 功能： SettingService接口
 */

var Logger = __webpack_require__(3);
var DeviceSetting = __webpack_require__(11);
var GeneralSetting = __webpack_require__(12);

var SettingService = function () {
    function SettingService() {
        _classCallCheck(this, SettingService);

        this.logger = new Logger();
        this._deviceSetting = DeviceSetting.getInstance();
        this._generalSetting = GeneralSetting.getInstance();
    }

    /**
     * 获取SettingService 单例
     * @returns {SettingService}  单例对象
     */


    _createClass(SettingService, [{
        key: "getGeneralSetting",


        /**
         * 获取一般化设置操作接口
         * @returns {*}
         */
        value: function getGeneralSetting() {
            return this._generalSetting;
        }

        /**
         * 获取设备设置操作接口
         * @returns {DeviceSetting|*}
         */

    }, {
        key: "getDeviceSetting",
        value: function getDeviceSetting() {
            return this._deviceSetting;
        }
    }], [{
        key: "getInstance",
        value: function getInstance() {
            if (SettingService.prototype.instance === undefined) {
                SettingService.prototype.instance = new SettingService();
            }
            return SettingService.prototype.instance;
        }
    }]);

    return SettingService;
}();

module.exports = SettingService;

/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by aragornzhao on 2018/05/14
 * 功能： 设备管理
 */

var Constants = __webpack_require__(2);
var Logger = __webpack_require__(3);
var WebRtcService = __webpack_require__(7);

var DeviceSetting = function () {
    function DeviceSetting() {
        _classCallCheck(this, DeviceSetting);

        this.logger = new Logger();
        this.rtc_service = WebRtcService.getInstance();
        this.onGetCameraDeviceListCallBack = this.onGetCameraDeviceListCallBack.bind(this);
        this.onGetMicDeviceListCallBack = this.onGetMicDeviceListCallBack.bind(this);
    }

    /**
     * 获取单例
      * @returns {DeviceSetting}
     */


    _createClass(DeviceSetting, [{
        key: "getDeviceList",


        /**
         * 获取设备列表
         * @param device_type 0：mic, 1 : camera
         * @returns {boolean}
         */
        value: function getDeviceList(device_type) {
            if (device_type === Constants.DeviceType.MIC) {
                this.rtc_service.registerEventHandler('get_audio_device', this.onGetMicDeviceListCallBack);
                this.rtc_service.getAudioDevices();
                return true;
            } else if (device_type === Constants.DeviceType.CAMERA) {
                this.rtc_service.registerEventHandler('get_video_device', this.onGetCameraDeviceListCallBack);
                this.rtc_service.getVideoDevices();
                return true;
            }

            return false;
        }

        /**
         * 选择设备
         * @param device 设备对象
         * @param device_type 设备类型 0：mic, 1 : camera
         * @returns {boolean}
         */

    }, {
        key: "select",
        value: function select(device, device_type) {
            if (device_type === Constants.DeviceType.MIC) {
                this.rtc_service.chooseAudioDevice(device);
                return true;
            } else if (device_type === Constants.DeviceType.MIC) {
                this.rtc_service.chooseVideoDevice(device);
                return true;
            }

            return false;
        }

        /**
         * MIC 获取回调
         * @param devices  mic集合
         */

    }, {
        key: "onGetMicDeviceListCallBack",
        value: function onGetMicDeviceListCallBack(devices) {
            var cb = this.getEventHandler('mic');
            cb(devices);
        }

        /**
         * 摄像头获取回调
         * @param devices camera集合
         */

    }, {
        key: "onGetCameraDeviceListCallBack",
        value: function onGetCameraDeviceListCallBack(devices) {
            var cb = this.getEventHandler('camera');
            cb(devices);
        }

        /**
         * 注释事件回调
         * @param event_key： 事件名称
         * @param callBackFun： 回调函数
         */

    }, {
        key: "registerEventHandler",
        value: function registerEventHandler(event_key, callBackFun) {
            var event_list = ['mic, camera'];
            if (event_list.indexOf(event_key) === -1) {
                return false;
            }
            this.eventListenersMap.set(event_key, callBackFun);
            return true;
        }

        /**
         * 获取事件回调函数
         * @param event_key: 事件名称
         * @returns {function} 回调函数
         */

    }, {
        key: "getEventHandler",
        value: function getEventHandler(event_key) {
            var cb = this.eventListenersMap.get(event_key);
            if (cb === undefined) {
                cb = function cb(devices) {};
            }

            return cb;
        }
    }], [{
        key: "getInstance",
        value: function getInstance() {
            if (DeviceSetting.prototype.instance === undefined) {
                DeviceSetting.prototype.instance = new DeviceSetting();
            }
            return DeviceSetting.prototype.instance;
        }
    }]);

    return DeviceSetting;
}();

module.exports = DeviceSetting;

/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by aragornzhao on 2018/05/14
 * 功能： 配置管理 - 一般性设置
 */

var Constants = __webpack_require__(2);
var Logger = __webpack_require__(3);
var XmppService = __webpack_require__(4);
var RTCService = __webpack_require__(7);

var GeneralSetting = function () {
    function GeneralSetting() {
        _classCallCheck(this, GeneralSetting);

        this.logger = new Logger();
        this.xmpp_service = XmppService.getInstance();
        this.rtc_service = RTCService.getInstance();
    }

    _createClass(GeneralSetting, [{
        key: "enableTestMode",


        /**
         * 连接测试环境
         * @param is_test true 测试环境， false 正式环境
         */
        value: function enableTestMode(is_test) {
            if (is_test) {
                this.xmpp_service.SERVER_URL = Constants.ConfWebSocketUrlTest;
            } else {
                this.xmpp_service.SERVER_URL = Constants.ConfWebSocketUrl;
            }
        }

        /**
         * 判断是否支持RTC
         */

    }, {
        key: "canSupportRTC",
        value: function canSupportRTC() {
            return this.rtc_service.canSupportRTC();
        }
    }], [{
        key: "getInstance",
        value: function getInstance() {
            if (GeneralSetting.prototype.instance === undefined) {
                GeneralSetting.prototype.instance = new GeneralSetting();
            }
            return GeneralSetting.prototype.instance;
        }
    }]);

    return GeneralSetting;
}();

module.exports = GeneralSetting;

/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * Created by aragornzhao on 2018/05/14
 * 功能： 预定会议管理
 */

var Constants = __webpack_require__(2);
var Logger = __webpack_require__(3);
var WebRtcService = __webpack_require__(7);
var XmppService = __webpack_require__(4);
var MeetingUserCtrl = __webpack_require__(6);

if (typeof console.assert === "undefined") {
    console.assert = function (val, msg) {
        // do nothing to pass
    };
}

var onJoinRepCheckPermissions = function onJoinRepCheckPermissions(that, data) {
    if (data.hasOwnProperty("permission_list")) {
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
            for (var _iterator = data.permission_list[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                var p = _step.value;

                if (p.hasOwnProperty("type")) {
                    if (p.type == Constants.MediaType.AUDIO) {
                        if (p.hasOwnProperty('is_grant') && p.is_grant === "0") {
                            that.savedAudioOn = "0";
                        }
                    } else if (p.type == Constants.MediaType.VIDEO) {
                        if (p.hasOwnProperty('is_grant') && p.is_grant === "0") {
                            that.savedVideoOn = "0";
                        }
                    }
                }
            }
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally {
            try {
                if (!_iteratorNormalCompletion && _iterator.return) {
                    _iterator.return();
                }
            } finally {
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }
    }
    if (data.hasOwnProperty("meeting_permission_list")) {
        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
            for (var _iterator2 = data.meeting_permission_list[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                var _p = _step2.value;

                if (_p.hasOwnProperty("type")) {
                    if (_p.type == Constants.MediaType.AUDIO) {
                        if (_p.hasOwnProperty('state') && _p.state == "2") {
                            that.savedAudioOn = "0";
                        }
                    } else if (_p.type == Constants.MediaType.VIDEO) {
                        if (_p.hasOwnProperty('state') && _p.state == "2") {
                            that.savedVideoOn = "0";
                        }
                    }
                }
            }
        } catch (err) {
            _didIteratorError2 = true;
            _iteratorError2 = err;
        } finally {
            try {
                if (!_iteratorNormalCompletion2 && _iterator2.return) {
                    _iterator2.return();
                }
            } finally {
                if (_didIteratorError2) {
                    throw _iteratorError2;
                }
            }
        }
    }
};

var PreMeetingManager = function () {
    function PreMeetingManager() {
        var _this = this;

        _classCallCheck(this, PreMeetingManager);

        this.logger = new Logger();
        this.xmpp_service = XmppService.getInstance();
        this.rtc_service = WebRtcService.getInstance();
        this.eventListenersMap = new Map();
        this.mediaRoomParams = {};
        this.meetingUserCtrl = MeetingUserCtrl.getInstance();

        this.savedNickName = '';
        this.savedVideoOn = true;
        this.savedAudioOn = true;
        this.savedJoinMeetingData = null;

        this.app_id = null; // to be set by sdk

        var bind_this = function bind_this(func_name) {
            return _this[func_name] = _this[func_name].bind(_this);
        };

        bind_this('joinMeeting');
        bind_this('dissolveMeeting');

        bind_this('onCreateMeetingCallBack');
        bind_this('onCancelMeetingCallBack');
        bind_this('onQueryMeetingItemListCallBack');
        bind_this('onUpdateMeetingCallBack');
        bind_this('onMeetingModifiedCallBack');

        bind_this('onJoinMeetingCallBack');
        bind_this('onDissolveMeetingCallBack');

        bind_this('onNotifySchedule');
        bind_this('onNotifyMeetingItemUpdate');

        bind_this('onCreateMediaRoomCallBack');
        bind_this('onInitRtcCallBack');
        bind_this('onLeaveMediaRoomCallBack');

        this.listenEvent();
    }

    _createClass(PreMeetingManager, [{
        key: "listenEvent",
        value: function listenEvent() {
            this.xmpp_service.registerEventHandler("create_meeting", this.onCreateMeetingCallBack);
            this.xmpp_service.registerEventHandler("cancel_meeting", this.onCancelMeetingCallBack);
            this.xmpp_service.registerEventHandler("query_meeting_item_list", this.onQueryMeetingItemListCallBack);
            this.xmpp_service.registerEventHandler("modify_meeting", this.onUpdateMeetingCallBack);
            this.xmpp_service.registerEventHandler("meeting_modified", this.onMeetingModifiedCallBack);
            this.xmpp_service.registerEventHandler("notify_schedule", this.onNotifySchedule);
            this.xmpp_service.registerEventHandler("notify_meeting_item_update", this.onNotifyMeetingItemUpdate);

            this.xmpp_service.registerEventHandler("join_meeting", this.onJoinMeetingCallBack);
            this.xmpp_service.registerEventHandler("dissolve_meeting", this.onDissolveMeetingCallBack);

            this.rtc_service.registerEventHandler("init", this.onInitRtcCallBack);
            this.rtc_service.registerEventHandler("create_room", this.onCreateMediaRoomCallBack);
            this.rtc_service.registerEventHandler("leave_room", this.onLeaveMediaRoomCallBack);
        }

        /**
         * 创建会议
         * @param createParams
         * subject | 会议主题
         * begin_time| 会议开始时间
         * end_time|会议结束时间
         * password|加入会议密码
         * location|会议地点
         * host | 主持人
         * custom_buffer|预留字段
         * invite_list array
         *      app_uid|与会成员ID
         *      app_id|与会成员appid
         */

    }, {
        key: "createMeeting",
        value: function createMeeting(createParams) {
            console.assert(createParams.hasOwnProperty("subject"), 'subject is necessary');
            console.assert(createParams.hasOwnProperty("begin_time"), 'begin_time is necessary');
            console.assert(createParams.hasOwnProperty("end_time"), 'end_time is necessary');
            console.assert(createParams.hasOwnProperty("host"), 'host is necessary');
            console.assert(createParams.hasOwnProperty("invite_list"), 'invite_list is necessary');

            this._formatParams(createParams, createParams, 'password', '');
            this._formatParams(createParams, createParams, 'custom_buffer', '');

            this.xmpp_service.createMeetingRequest(createParams);
            return true;
        }

        /**
         * 查询会议详情列表
         * @param queryParams
         *      begin_time | 开始时间,	缺省或为0时不限定开始时间
         *      end_time | 	结束时间,缺省或为0时不限定结束时间
         *      creator_uid | 会议创建者的app_uid,缺省时不限定该条件。 如果带此字段，则只查询该用户创建的会议
         *      is_creator | 本人为创建者,缺省时不限定该条件。如果为true，则只查询该用户创建的会议，如果为false，则不查询该用户创建的会议。
         *      is_invitee| 本人为被邀请者,缺省时不限定该条件。如果为true，则只查询邀请该用户的会议，如果为false，则不查询邀请该用户的会议。
         */

    }, {
        key: "internalQueryMeetingItemList",
        value: function internalQueryMeetingItemList(queryParams) {
            var params = {};

            this._formatParams(params, queryParams, 'begin_time', null);
            this._formatParams(params, queryParams, 'end_time', null);
            this._formatParams(params, queryParams, 'meeting_id', 0);
            this._formatParams(params, queryParams, 'meeting_code', null);
            this._formatParams(params, queryParams, 'creator_uid', null);
            this._formatParams(params, queryParams, 'is_creator', null);
            this._formatParams(params, queryParams, 'is_invitee', null);
            this._formatParams(params, queryParams, 'expect_meeting_count', 10);
            this._formatParams(params, queryParams, 'meeting_last_modify_time', null);

            this.xmpp_service.queryMeetingItemListRequest(params);
            return true;
        }

        /**
         * 通过会议id查询会议详情
         * @param {string} meeting_id 
         */

    }, {
        key: "queryMeetingItemById",
        value: function queryMeetingItemById(meeting_id) {
            this.internalQueryMeetingItemList({
                meeting_id: meeting_id
            });
        }

        /**
         * 通过会议码查询会议详情
         * @param {string} meeting_code 
         */

    }, {
        key: "queryMeetingItemByCode",
        value: function queryMeetingItemByCode(meeting_code) {
            this.internalQueryMeetingItemList({
                meeting_code: meeting_code
            });
        }

        /**
         * 查询会议简要信息列表
         * @param {number} last_modified_time 后台会返回该时间之前的条目
         */

    }, {
        key: "queryMeetingBriefList",
        value: function queryMeetingBriefList() {
            var last_modified_time = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;

            console.log('queryMeetingBriefList called with time:', last_modified_time);
            this.internalQueryMeetingItemList({
                meeting_last_modify_time: last_modified_time.toString(),
                expect_meeting_count: 10
            });
        }

        /**
         * 通话会议ID查询会议详情
         * @param meeting_id
         */

    }, {
        key: "queryMeetingItem",
        value: function queryMeetingItem(meeting_id) {
            var queryParams = {
                begin_time: 0,
                end_time: 0,
                creator_uid: '',
                is_creator: '',
                is_invitee: '',
                meeting_id: meeting_id
            };
            this.xmpp_service.queryMeetingItemListRequest(queryParams);
            return true;
        }

        /**
         * 通话会议ID删除会议
         * @param meeting_id
         */

    }, {
        key: "cancelMeeting",
        value: function cancelMeeting(meeting_id) {
            var cancelParams = {
                meeting_id: meeting_id,
                reason: '',
                code: ''
            };
            this.xmpp_service.cancelMeetingRequest(cancelParams);
            return true;
        }
    }, {
        key: "updateMeeting",
        value: function updateMeeting(updateParam) {
            console.assert(updateParam.hasOwnProperty('meeting_id') && updateParam.meeting_id > 0, 'meeting_id is necessary');
            var params = { meeting_id: updateParam.meeting_id };
            this._formatParams(params, updateParam, 'subject', null);
            this._formatParams(params, updateParam, 'begin_time', null);
            this._formatParams(params, updateParam, 'end_time', null);
            this._formatParams(params, updateParam, 'password', null);
            this._formatParams(params, updateParam, 'host', null);
            this._formatParams(params, updateParam, 'invite_list', null);
            this._formatParams(params, updateParam, 'location', null);

            this.xmpp_service.modifyMeetingItemRequest(params);
            return true;
        }

        /**
         * 加入会议
         * @param join_param 加入参数
         *      meeting_code|app层传递的meeting code
         *      nickname|用户名
         *      password|密码
         *      video_on|加入房间后摄像头默认状态
         *      audio_on|加入房间后音频默认状态
         *      user_id | 音视频openid
         *      sdk_appid | 开放 sdk_appid
         *      account_type | 开放 accountType
         *      user_sig| 从腾讯云计算的sig
         *      room_id | 音视频房间号
         *      private_key | 腾讯云私钥
         *      role | 腾讯云角色
         */

    }, {
        key: "joinMeeting",
        value: function joinMeeting(join_param) {
            console.assert(join_param.hasOwnProperty('meeting_id') || join_param.hasOwnProperty('meeting_code'), 'meeting_id or meeting_code is necessary');
            console.assert(join_param.hasOwnProperty('nickname'), 'nickname is necessary');
            console.assert(join_param.nickname.length > 0, 'nickname is invalid');

            var castBool = function castBool(keyList) {
                var _iteratorNormalCompletion3 = true;
                var _didIteratorError3 = false;
                var _iteratorError3 = undefined;

                try {
                    for (var _iterator3 = keyList[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
                        var keyName = _step3.value;

                        if (typeof join_param[keyName] === 'boolean' || typeof join_param[keyName] === 'number') {
                            join_param[keyName] = join_param[keyName] ? "1" : "0";
                        }
                    }
                } catch (err) {
                    _didIteratorError3 = true;
                    _iteratorError3 = err;
                } finally {
                    try {
                        if (!_iteratorNormalCompletion3 && _iterator3.return) {
                            _iterator3.return();
                        }
                    } finally {
                        if (_didIteratorError3) {
                            throw _iteratorError3;
                        }
                    }
                }
            };

            var boolKeyList = ['video_on', 'audio_on', 'share_on'];
            castBool(boolKeyList);

            var params = {};
            this._formatParams(params, join_param, 'meeting_id', null);
            this._formatParams(params, join_param, 'meeting_code', null);
            this._formatParams(params, join_param, 'nickname', '会议用户');
            this._formatParams(params, join_param, 'password', null);
            this._formatParams(params, join_param, 'video_on', true);
            this._formatParams(params, join_param, 'audio_on', true);
            this._formatParams(params, join_param, 'share_on', false);

            this.savedNickName = params.nickname;
            this.savedVideoOn = params.video_on;
            this.savedAudioOn = params.audio_on;

            this.meetingUserCtrl.reset();
            this.xmpp_service.joinMeetingRequest(params);
            return true;
        }

        /**
         * 解散会议
         * @param meeting_id
         */

    }, {
        key: "dissolveMeeting",
        value: function dissolveMeeting(meeting_id) {
            console.assert(meeting_id > 0, 'meeting_id is necessary');
            var meetingParam = {
                meeting_id: meeting_id,
                reason: '1', // 0:None 1:主持人解散会议
                code: '0'
            };
            this.xmpp_service.dissolveMeetingRequest(meetingParam);
            return true;
        }

        /**
         * 注释事件回调
         * @param event_key： 事件名称
         * @param callback： 回调函数
         */

    }, {
        key: "registerEventHandler",
        value: function registerEventHandler(event_key, callback) {
            var event_list = ['create_meeting', 'cancel_meeting', 'query_meeting_item_list', 'update_meeting', 'join_meeting', 'dissolve_meeting', 'leave_room', 'meeting_modified', 'notify_schedule', 'notify_meeting_item_update'];
            if (event_list.indexOf(event_key) === -1) {
                console.log('Premeeting registerEventHandler adding an unrecognized event:', event_key);
                return false;
            }

            if (typeof callback === "function") {
                this.eventListenersMap.set(event_key, callback);
                return true;
            }

            return false;
        }

        /**
         * 获取事件回调函数
         * @param event_key: 事件名称
         * @returns {function} 回调函数
         */

    }, {
        key: "getEventHandler",
        value: function getEventHandler(event_key) {
            var cb = this.eventListenersMap.get(event_key);
            if (cb === undefined) {
                cb = function cb() {};
            }
            return cb;
        }
    }, {
        key: "onQueryMeetingItemListCallBack",
        value: function onQueryMeetingItemListCallBack(flag, data) {
            var cb = this.getEventHandler('query_meeting_item_list');
            cb(flag, data);
        }
    }, {
        key: "onCreateMeetingCallBack",
        value: function onCreateMeetingCallBack(flag, data) {
            var cb = this.getEventHandler('create_meeting');
            if ((typeof data === "undefined" ? "undefined" : _typeof(data)) === 'object') {
                console.log('schedule rep data:', JSON.stringify(data));
            }
            cb(flag, data);
        }
    }, {
        key: "onUpdateMeetingCallBack",
        value: function onUpdateMeetingCallBack(flag, data) {
            var cb = this.getEventHandler('update_meeting');
            cb(flag, data);
        }
    }, {
        key: "onMeetingModifiedCallBack",
        value: function onMeetingModifiedCallBack(flag, data) {
            var cb = this.getEventHandler('meeting_modified');
            cb(flag, data);
        }
    }, {
        key: "onNotifySchedule",
        value: function onNotifySchedule(flag, data) {
            var cb = this.getEventHandler('notify_schedule');
            cb(flag, data);
        }
    }, {
        key: "onNotifyMeetingItemUpdate",
        value: function onNotifyMeetingItemUpdate(flag, data) {
            var cb = this.getEventHandler('notify_meeting_item_update');
            cb(flag, data);
        }
    }, {
        key: "onQueryMeetingItemCallBack",
        value: function onQueryMeetingItemCallBack(flag, data) {
            var cb = this.getEventHandler('query_meeting_item');
            cb(flag, data);
        }
    }, {
        key: "onCancelMeetingCallBack",
        value: function onCancelMeetingCallBack(flag, data) {
            var cb = this.getEventHandler('cancel_meeting');
            cb(flag, data);
        }
    }, {
        key: "onJoinMeetingCallBack",
        value: function onJoinMeetingCallBack(flag, data) {
            if ((typeof data === "undefined" ? "undefined" : _typeof(data)) === 'object') {
                console.log('join meeting rep data:', JSON.stringify(data));
            }
            var cb = this.getEventHandler('join_meeting');
            if (!flag) {
                cb(flag, data);
                return;
            }

            onJoinRepCheckPermissions(this, data);

            var enableAudio = this.savedAudioOn && this.savedAudioOn !== "0" ? true : false;
            var enableVideo = this.savedVideoOn && this.savedVideoOn !== "0" ? true : false;

            var getUidFromJid = function getUidFromJid(jid) {
                return jid.split("/")[0];
            };
            var selfUid = getUidFromJid(this.xmpp_service.jid);

            this.mediaRoomParams = {
                // user_id: data.av_user_id,
                // user_id: selfUid,
                user_id: [Constants.INSTANCE_ID.toString(), selfUid, this.app_id].join('_'),
                user_sig: data.qcloud_user_signature,
                sdk_appid: this.app_id,
                account_type: 31778, // 31778 for 1400115281
                is_enable_audio: enableAudio,
                is_enable_video: enableVideo,
                room_id: data.av_room_id,
                private_key: data.qcloud_user_private_map_key,
                role: "user"
            };

            this.savedJoinMeetingData = data;
            this.savedJoinMeetingData.room_user_id = this.mediaRoomParams.user_id;
            this.logger.debug("Premeeting onJoinMeetingCallBack data:", data);

            if (Constants.INSTANCE_ID === Constants.InstanceType.INSTANCE_WEB) {
                this.logger.debug("initWebRtc with param data:", JSON.stringify(this.mediaRoomParams));
                this.rtc_service.initWebRtc(this.mediaRoomParams);
                /** next step to: this.onInitRtcCallBack */
            } else {
                /** for mini program will return immediately */
                this.meetingUserCtrl.setMeetingId(this.savedJoinMeetingData.meeting_id);
                this.meetingUserCtrl.setSelfUserId(selfUid);
                this.meetingUserCtrl.setSelfNickname(this.savedNickName);
                this.meetingUserCtrl.updateUserInfo({
                    nickname: this.savedNickName,
                    video_on: this.savedVideoOn,
                    video_reason: Constants.SwitchReason.BYSELF,
                    audio_on: this.savedAudioOn,
                    audio_reason: Constants.SwitchReason.BYSELF,
                    share_on: 0,
                    share_reason: Constants.SwitchReason.BYSELF
                }, Constants.UserState.JOIN);
                cb(true, this.savedJoinMeetingData);
            }
        }
    }, {
        key: "onInitRtcCallBack",
        value: function onInitRtcCallBack(flag, data) {
            if (!flag) {
                this.savedJoinMeetingData.initRTCInfo = {};
                this.savedJoinMeetingData.initRTCInfo.msg = "init rtc failed";
                this.savedJoinMeetingData.initRTCInfo.data = data;
                console.log('Premeeting onInitRtcCallBack calling back join_meeting, data:', this.savedJoinMeetingData);
                var cb = this.getEventHandler('join_meeting');
                cb(flag, this.savedJoinMeetingData);
                return;
            }
            this.rtc_service.createRoom(this.mediaRoomParams);
            /** next step to: this.onCreateMediaRoomCallBack */
        }
    }, {
        key: "onCreateMediaRoomCallBack",
        value: function onCreateMediaRoomCallBack(flag, data) {
            var cb = this.getEventHandler('join_meeting');
            this.savedJoinMeetingData.initRTCInfo = {};
            this.savedJoinMeetingData.initRTCInfo.data = data;
            if (!flag) {
                this.savedJoinMeetingData.initRTCInfo.msg = "enter media room failed";
                cb(flag, this.savedJoinMeetingData);
                return;
            }

            var getUidFromJid = function getUidFromJid(jid) {
                return jid.split("/")[0];
            };
            this.meetingUserCtrl.setMeetingId(this.savedJoinMeetingData.meeting_id);
            this.meetingUserCtrl.setSelfUserId(getUidFromJid(this.xmpp_service.jid));
            this.meetingUserCtrl.setSelfNickname(this.savedNickName);
            this.meetingUserCtrl.updateUserInfo({
                nickname: this.savedNickName,
                video_on: this.savedVideoOn,
                video_reason: Constants.SwitchReason.BYSELF,
                audio_on: this.savedAudioOn,
                audio_reason: Constants.SwitchReason.BYSELF,
                share_on: 0,
                share_reason: Constants.SwitchReason.BYSELF
            }, Constants.UserState.JOIN);

            cb(true, this.savedJoinMeetingData);
        }
    }, {
        key: "onDissolveMeetingCallBack",
        value: function onDissolveMeetingCallBack(flag, data) {
            var cb = this.getEventHandler('dissolve_meeting');
            cb(flag, data);
        }
    }, {
        key: "onLeaveMediaRoomCallBack",
        value: function onLeaveMediaRoomCallBack(flag, data) {
            if (!flag) {
                console.error("rtc leave room fail");
            }

            var cb = this.getEventHandler('leave_room');
            cb(flag, data);
        }
    }, {
        key: "_formatParams",
        value: function _formatParams(out, inParams, key, default_value) {
            if (inParams.hasOwnProperty(key)) {
                out[key] = inParams[key];
            } else if (default_value !== null) {
                out[key] = default_value;
            }
        }
    }], [{
        key: "getInstance",
        value: function getInstance() {
            if (PreMeetingManager.prototype.instance === undefined) {
                PreMeetingManager.prototype.instance = new PreMeetingManager();
            }
            return PreMeetingManager.prototype.instance;
        }
    }]);

    return PreMeetingManager;
}();

module.exports = PreMeetingManager;

/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Scout = function () {
  function Scout() {
    _classCallCheck(this, Scout);
  }

  _createClass(Scout, [{
    key: "checkTBSVersion",
    value: function checkTBSVersion() {
      var list = navigator.userAgent.split(" ");
      var isTBS = false;
      var TBSVersion = 0;
      var TBS_MIN_VERSION = 43600;
      for (var i = 0; i < list.length; i++) {
        var item = list[i];
        if (item.indexOf("TBS") !== -1 || item.indexOf("tbs") !== -1) {
          isTBS = true;
          var versionStr = item.split("/")[1];
          var version = parseInt(versionStr) || 0;
          TBSVersion = version;
        }
      }
      return {
        isTBS: isTBS,
        TBSversion: TBSVersion,
        isTBSValid: TBSVersion >= TBS_MIN_VERSION
      };
    }
  }, {
    key: "isFF",
    value: function isFF() {
      return navigator.userAgent.toLowerCase().indexOf("firefox") !== -1;
    }
  }, {
    key: "isChrome",
    value: function isChrome() {
      return (/Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)
      );
    }
  }, {
    key: "isSafari",
    value: function isSafari() {
      var ua = navigator.userAgent.toLowerCase();
      var fd = function fd(ss) {
        return ua.indexOf(ss) > -1;
      };
      var nf = function nf(ss) {
        return ua.indexOf(ss) === -1;
      };
      var a = fd('safari/');
      var b = nf('chrome/');
      var c = nf('qq/') && nf('mqqbrowser');
      return a && b && c;
    }
  }, {
    key: "isiOS",
    value: function isiOS() {
      return (/iPhone|iPad|iPod/i.test(navigator.userAgent)
      );
    }
  }, {
    key: "isQQ",
    value: function isQQ() {
      return (/QQ|SQ/.test(navigator.userAgent)
      );
    }
  }, {
    key: "isWX",
    value: function isWX() {
      return (/MicroMessenger/.test(navigator.userAgent)
      );
    }
  }, {
    key: "isMQQBrowser",
    value: function isMQQBrowser() {
      return (/MQQBrowser/.test(navigator.userAgent)
      );
    }
  }, {
    key: "getiOSVersion",
    value: function getiOSVersion() {
      var matches = navigator.userAgent.match(/OS (\d+)_(\d+)_?(\d+)?/);
      return matches && [parseInt(matches[1]), parseInt(matches[2]), parseInt(matches[3] || 0)] || false;
    }
  }, {
    key: "getSafariVersion",
    value: function getSafariVersion() {
      var matches = navigator.userAgent.match(/Version\/(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
      return matches && [parseInt(matches[1]), parseInt(matches[2] || 0), parseInt(matches[3] || 0)] || false;
    }
  }, {
    key: "checkH264Support",
    value: function checkH264Support(callback) {
      if (!('RTCPeerConnection' in window)) {
        callback(false);
        return;
      }
      try {
        var peer = new RTCPeerConnection(null);
        peer.createOffer({
          offerToReceiveAudio: 1,
          offerToReceiveVideo: 1
        }).then(function (data) {
          if (data.sdp.toLowerCase().indexOf("h264") === -1) {
            callback(false);
          } else {
            callback(true);
          }
          peer.close();
        }, function (err_data) {
          callback(false);
        });
      } catch (err) {
        callback(false);
      }
    }
  }, {
    key: "isSupportWebRTC",
    value: function isSupportWebRTC() {
      var isWebRTCSupported = false;
      ['RTCPeerConnection', 'webkitRTCPeerConnection', 'RTCIceGatherer'].forEach(function (item) {
        if (isWebRTCSupported) {
          return;
        }
        if (item in window) {
          isWebRTCSupported = true;
        }
      });
      var TBSInfo = this.checkTBSVersion();
      if (!TBSInfo.isTBS) {
        if (this.isFF()) {
          isWebRTCSupported = false;
        } else if (this.isSafari()) {
          var iOSVersion = this.getiOSVersion();
          var safariVersion = this.getSafariVersion();

          if (iOSVersion) {
            if (iOSVersion[0] >= 11 && iOSVersion[1] >= 1) {
              // do nothing
            } else {
              isWebRTCSupported = false;
            }
          } else if (safariVersion) {
            if (safariVersion[0] >= 11 && safariVersion[1] >= 1) {
              // do nothing
            } else {
              isWebRTCSupported = false;
            }
          } else {
            isWebRTCSupported = false;
          }
        } else if (this.isQQ() || this.isWX() || this.isMQQBrowser()) {
          isWebRTCSupported = false;
        }
      } else {
        if (!TBSInfo.isTBSValid) {
          isWebRTCSupported = false;
        }
      }

      var ret = {
        support: isWebRTCSupported,
        isTBS: TBSInfo.isTBS,
        isTBSValid: TBSInfo.isTBSValid,
        TBSversion: TBSInfo.TBSversion,
        isSafari: this.isSafari(),
        iOSVersion: this.getiOSVersion(),
        screenshare: false,
        isFF: this.isFF()
      };

      this.checkH264Support(function (support) {
        ret.h264Support = support;
        if (!support) {
          ret.support = false;
        }
      });
      return ret.support;
    }
  }], [{
    key: "getInstance",
    value: function getInstance() {
      if (Scout.prototype.instance === undefined) {
        Scout.prototype.instance = new Scout();
      }
      return Scout.prototype.instance;
    }
  }]);

  return Scout;
}();

module.exports = Scout;

/***/ })
/******/ ]);